我對 Python 比較陌生,剛開始接觸函式。我正在撰寫一個示例,但不太明白如何撰寫所需的函式。
該函式的輸入是以下格式的字串串列:
lines = ['1: 362.5815 162.5823\n',
'2: 154.1328 354.1330\n',
'3: 168.9325 368.9331\n',.. ]
我必須創建一個函式,將串列中的每個專案轉換為一個元組,并將輸出存盤在一個新串列中。
要將串列的單個專案轉換為元組,我使用以下代碼:
```python
f1 = lines[0].split(" ")
f1tuple1 = tuple(f1)
f1tuple2 = (f1tuple[0], [float(f1tuple[1]), float(f1tuple[2])])
How do I perform the same action for all of the items in the list?
I would really appreciate help in this matter.
uj5u.com熱心網友回復:
編輯:正如評論中正確指出的那樣,不需要使用地圖。
我使用函式和正確的型別進行了更新(第一個元組元素為 int):
lines = ['1: 362.5815 162.5823\n', '2: 154.1328 354.1330\n', '3: 168.9325 368.9331\n']
def create_tuples(lines):
return [(int((y := x.split(" "))[0].strip(':')),
[float(y[1]), float(y[2].strip('\n'))]
) for x in lines]
print(create_tuples(lines))
輸出:
[(1, [362.5815, 162.5823]), (2, [154.1328, 354.133]), (3, [168.9325, 368.9331])]
注意:串列推導中的賦值僅適用于 python >= 3.8
舊答案:
您可以使用map:
fituples = list(map(lambda x: tuple(x.strip("\n").split(" ")), lines))
輸出:
[('1:', '362.5815', '162.5823'), ('2:', '154.1328', '354.1330'), ('3:', '168.9325', '368.9331')]
uj5u.com熱心網友回復:
使用“for”回圈,您可以遍歷串列中的所有專案:
all_tuples = [] #<-- create a list to put all you tuples into
for value in lines: #<-- for loop, running through all values in you lines list
f1 = value.split(" ") #<-- your code1
f1tuple = tuple(f1) #<-- your code2
f1tuple2 = (f1tuple[0], [float(f1tuple[1]), float(f1tuple[2])]) #<-- your code3
all_tuples.append(f1tuple2) #<-- Adding the tuple to the list
all_tuples
[('1:', [362.5815, 162.5823]),
('2:', [154.1328, 354.133]),
('3:', [168.9325, 368.9331])]
作為一個函式:
def get_all_tuples(lines): #<-- create a function
all_tuples = []
for value in lines:
f1 = value.split(" ")
f1tuple = tuple(f1)
f1tuple2 = (f1tuple[0], [float(f1tuple[1]), float(f1tuple[2])])
all_tuples.append(f1tuple2)
return all_tuples #<-- return your all_tuples list
uj5u.com熱心網友回復:
def items(lines):
vals = [x.split(" ") for x in lines]
return [(i[0], i[1], i[2]) for i in vals]
uj5u.com熱心網友回復:
使用re:
tuples = []
for item in lines:
if m := re.match(r"(\d ):\s (\S )\s (\S )", item):
tuples.append([m.group(1), (m.group(2), m.group(3))])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363891.html
