gpt4 book ai didi

python - 返回要索引的文本文件中的项目列表

转载 作者:行者123 更新时间:2023-12-01 05:55:00 25 4
gpt4 key购买 nike

我正在尝试编写一个从文本文件返回城市列表的函数,以便在调用该函数时,您可以在其后面放置一个索引,它将返回相应的城市。

示例:

citylist('MYFILE.txt')[3]

到目前为止,我已经

def citylist(filename):
assert type(filename)==str

with open(filename) as FileObject:
for line in FileObject:
q=line.split('\t')
print q[12],

有 500 条投诉。当我将每个字符串(投诉)拆分为一个列表后,城市名称是列表中的第 13 个索引。但我陷入困境,因为我所能做的就是将所有城市名称打印为无法索引的非数据类型。

最佳答案

您可以创建一个列表并返回它:

def citylist(filename):
assert type(filename)==str #isinstance(filename,str) is more idiomatic here.

output = []
with open(filename) as FileObject:
for line in FileObject:
q = line.split('\t')
output.append(q[12])
return output

或者,更简洁:

def citylist(filename):
with open(filename) as f:
return [ line.split('\t')[12] for line in f ]

我使用 list-comprehension 构建了列表在最后一个例子中。

关于python - 返回要索引的文本文件中的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13021549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com