我有一个这样的输入文件:
5181 zzzzzzzzzzzzzzzz
6220 aaaaaaaa
1498 bbbbbbbbb
1498 ccccccccccc
我想对具有相同 ID 号的行进行分组。所以它会是这样的:
5181 zzzzzzzzzzzzzzzz
6220 aaaaaaaa
1498 bbbbbbbbbb
1498 ccccccccccc
我试图创建一个包含 3 个键的字典,但无法附加所有值。
这是我写的:
for i in package_ids:
dict2[i] = (x for x in textt if int(i) in textt is True)
请您参考如下方法:
假设id号和行的文本用制表符(s)\t分隔,简单排序:
with open('yourfile.txt', 'r') as f:
lines = f.read().splitlines()
result = sorted(lines, key=lambda x: x[:x.find('\t')])
for l in result:
print(l)
输出:
1498 Pursuing it with eager feet,
1498 And I must follow, if I can,
1498 Until it joins some larger way
1498 The Road goes ever on and on
5181 not a penny-piece or a glass bead was given away.
5181 as well as the books, pictures were left in his possession.
6220 written in golden ink.
6220 There were many Bagginses and Boffins,
6220 of them had hardly ever been in Hobbiton before.
