简体   繁体   English

如何在 Python 中将文本文件(每个单独的项目在自己的行上)读入 2D 列表

[英]How to read a text file (each individual item on its own line) into a 2D list in Python

Trying to read a text file into a 2D list in Python.尝试将文本文件读入 Python 中的 2D 列表。 "people2.txt" is single lines in sequence (each item on its own line) “people2.txt”是单行顺序(每个项目在自己的行上)

fred
23
ann
27
bob
24

Code so far:到目前为止的代码:

details_list=[]

people2=open("people2.txt","r")

for line in people2.readlines():
    details_list.append(line.split())

people2.close()

print(details_list)

What I'm getting is each element in its own list, when I need "pairs"?当我需要“配对”时,我得到的是它自己列表中的每个元素? I'm getting我越来越

[["fred"],["23"],["ann"],["27"],["bob"],["24"]]

What I need is:我需要的是:

[["fred","23"],["ann","27"],["bob","24"]]

Use:用:

with open("people.txt") as infile:
    res = []
    for name, value in zip(infile, infile):
        res.append([name.strip(), value.strip()])
print(res)

Output输出

[['fred', '23'], ['ann', '27'], ['bob', '24']]

The expression:表达方式:

for name, value in zip(infile, infile):

allows you to iterate in chunks of two lines over the file, as a side note you should also use a context manager to read files.允许您在文件上以两行的块进行迭代,作为旁注,您还应该使用上下文管理器来读取文件。

If you already have a flat list of strings (which you will have if you replace line.split() with line.strip() ), you can take 2 slices of that list with step 2 (ie one slice has the even-indexed elements, the other has the odd-indexed elements), then use zip to pair them up:如果你已经有一个字符串的平面列表(如果更换,你将有line.split()line.strip()你可以把2片该列表的第2步(即一个片具有偶数索引元素,另一个具有奇数索引元素),然后使用zip将它们配对:

lines = ["Fred", "23", "Ann", "27", "Bob", "24"]
pairs = list(zip(lines[::2], lines[1::2]))
print(pairs)

This outputs这输出

[('Fred', '23'), ('Ann', '27'), ('Bob', '24')]

This works beyond just file reading, but if you have a large file, it would be more performant to just read them as pairs to begin with.这不仅适用于文件读取,但如果您有一个大文件,则开始时将它们成对读取会更高效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM