如何将文件中的元素放入三维列表中?Python

2024-04-20 11:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试找出如何将文件中的元素放入三维列表中。你知道吗

例如,如果我的人物.txt文件看起来像:

3 4   

SallyLee
MallieKim
KateBrown
JohnDoe
TreyGreen
SarahKind

但我只想在3D列表中使用SallyLee等,而不使用最前面的数字。你知道吗

到目前为止,我已经编码了:

def main(): 
    list = []


    peopleFile = open("people.txt")
    peopleRead = peopleFile.readlines()

    for lines in peopleRead:
        list.append([lines])

    peopleFile.close()
    print(list)
main()

然后打印数字,而不是3D列表。你知道吗

我想做的一个例子是:

[[[SallyLee],[MallieKim],[KateBrown]],[[JohnDoe],[TreyGreen],[SarahKind]]]

每一个第三者被“组合”在一起。你知道吗

我不希望任何人为我编写任何代码!

我只希望有人能把我引向正确的方向。你知道吗

谢谢


Tags: 文件txt列表main数字listlinesjohndoe
1条回答
网友
1楼 · 发布于 2024-04-20 11:24:45

首先,如果您要查找的只是字符串(而不是数字),那么您可以通过一个条件来启动for循环,以传递任何有数字的元素。您可以使用try:/except:来实现这一点。 接下来,您可以使用range函数的参数来列出您感兴趣的索引。如果你想按三分组,你可以让range列出三的倍数(0,3,6,9,…)

这是我的密码:

file = open('text.txt','r')

i = 0
names = []
for line in file:
    line.split() #This will split each line into a list
    try: #This will try to convert the first element of that list into an integer
        if int(line[0]):  #If it fails it will go to the next line
            continue
    except:
        if not line.strip(): #This will skip empty lines
            continue
        names.append(line.strip()) #First let's put all of the names into a list


names = [names[i:i+3] for i in range(0,len(names)-1,3)]
print names

输出:

[['SallyLee', 'MallieKim', 'KateBrown'], ['JohnDoe', 'TreyGreen', 'SarahKind']]

相关问题 更多 >