[英]How do I print each element of a list on individual lines, preceded by the line number in python?
[英]How i print each second element in a list full of lines? Python
我有一個這樣的數字列表(保存在 .txt 文件中):
list_of_numbers = [
('5', 2.5, 5200),
('6', 3.2, 5236),
('8', 5.4, 5287),
('6', 8.7, 2563)
]
我像這樣導入了這個列表(列表是 .txt 文件):
list_of_numbers = open("list_of_numbers.txt").read().strip().split()
但現在我希望 python 打印每行中的每個第二個元素..我試過這個:
p = x[1] for x in list_of_numbers
print(p)
但它不正確..我希望python像這樣打印我:
p = 2.5, 3.2, 5.4
請幫我..
你錯過了括號。 嘗試這個:
p = [x[1] for x in list_of_numbers]
要打印值,您可以使用
print(', '.join([str(x) for x in p]))
您還需要更改從文件加載數據的方式
完整代碼:
def parse(raw):
data = []
for line in raw.split("\n"):
line = line.strip()
# --> "('5', 2.5, 5200)"
if line.startswith("(") and line.endswith(")"):
d = line[line.index("(")+1 : line.index(")", -1)]
# --> "'5', 2.5, 5200"
d = d.split(",")
data.append([])
for i in d:
i = i.strip()
try:
i = float(i)
except:
pass
data[-1].append(i)
return data
raw = open("list_of_numbers.txt").read()
list_of_numbers = parse(raw)
p = [x[1] for x in list_of_numbers]
# --> [2.5, 3.2, 5.4, 8.7]
print(', '.join([str(x) for x in p]))
# ---> 2.5, 3.2, 5.4, 8.7
我建議使用pickle 。 存儲和加載您的數據很容易,因為:
import pickle
data = ...
# store
file = open('data.txt', 'w')
pickle.dump(data, file)
file.close()
# load
file = open('data.txt', 'r')
data = pickle.load(file)
file.close()
另一種選擇是使用numpy.ndarray
。
import numpy as np
list_of_numbers = [
('5', 2.5, 5200),
('6', 3.2, 5236),
('8', 5.4, 5287),
]
list_of_numbers = np.array(list_of_numbers)
p = list_of_numbers[:,1]
print(p)
# outputs: ['2.5' '3.2' '5.4']
此外,由於您正在從文本文件中讀取數據,因此您的第一個列表應僅包含str
。 (我真的不明白如何使用您在問題中描述的方法獲得混合的字符串和數字。)要解決這個問題,您可以:
numpy.loadtxt
,float
:`np.array(list_of_numbers, dtype=float)。最后,我強烈建議您學習Python 中的切片。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.