我如何在满是行的列表中打印每个第二个元素? 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,
  • 切换到 ndarray 时转换为 float:`np.array(list_of_numbers, dtype=float).

最后,强烈建议大家了解一下slices in Python