Python 将文本文件中的两列追加到单个列表中
我有一个空格分隔的文本文件(temp.txt),如下所示:Python 将文本文件中的两列追加到单个列表中,python,python-3.x,Python,Python 3.x,我有一个空格分隔的文本文件(temp.txt),如下所示: a susan python b rick java c bella scala {'susan python', 'rick java', 'bella scala'} 我想把它读成一组,如下所示: a susan python b rick java c bella scala {'susan python', 'rick java', 'bella scala'} 我尝试了以下代码,但它只返回{'bella scala'}
a susan python
b rick java
c bella scala
{'susan python', 'rick java', 'bella scala'}
我想把它读成一组,如下所示:
a susan python
b rick java
c bella scala
{'susan python', 'rick java', 'bella scala'}
我尝试了以下代码,但它只返回{'bella scala'}
temp_List = [];
with open('temp.txt', 'r') as f:
for line in f:
splitLine = line.split();
master_set = [" ".join(splitLine[1:])];
temp_Set = set(temp_List);
这是函数工作得非常好的情况之一
temp_set = set()
with open('temp.txt', 'r') as f:
for line in f:
_, _, name = line.partition(' ')
temp_set.add(name)
也可以更换
_, _, name = line.partition(' ')
与
代码不起作用的原因:
临时列表
,因此临时设置
也为空master\u set
在每次迭代中都会被覆盖,并且在最后一次迭代中通过此赋值['bella scala']
被赋值=[“”。join(splitLine[1:])]
您的代码不起作用,因为您没有将结果附加到
temp\u列表
对于这个问题,您可以将csv
模块与字典理解一起使用csv.reader
返回一个迭代器,该迭代器随后提供理解
from io import StringIO
import csv
mystr = StringIO("""a susan python
b rick java
c bella scala""")
# replace mystr with open('temp.txt', 'r')
with mystr as f:
reader = csv.reader(f, delimiter=' ')
res = {' '.join(i[1:]) for i in reader}
print(res)
{'susan python', 'rick java', 'bella scala'}
为此,您只需使用arrayappend函数并删除temp\u Set=Set(temp\u列表) 在这里,我们只需附加元素即可获得输出:
['susan python', 'rick java', 'bella scala']
@TanviP,您可以尝试以下代码 注意:
set()
不保留列表等元素的顺序。因此,如果顺序很重要,最好使用list,否则您需要使用OrderedDict()等第三方库
我使用了列表和集来说明两者的区别。将更多数据行添加到temp.txt,并运行代码以查看项目顺序的差异(有时您会发现将的元素设置为与相应的列表不同的顺序)
谢谢
temp_ordered_list = []
with open("temp.txt") as f:
for line in f.readlines():
data_list = line.strip().split()
temp_ordered_list.append(" ".join(data_list[1:]))
temp_unordered_set = set(temp_ordered_list)
print(temp_ordered_list); # ['susan python', 'rick java', 'bella scala'}
print(temp_unordered_set); # {'susan python', 'rick java', 'bella scala'}