gpt4 book ai didi

Python:基于相同元素对多个列表进行分组

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:44 25 4
gpt4 key购买 nike

所以我有一个制表符分隔的文本文件,如下所示:

23      Hello How are you?
23 What's up?
24 I am using Python

我想把上面的数据分开并分组,这样看起来是这样的:

23      Hello How are you? What's up?
24 I am using Python

基本上我想将第一列相同值的文本分组(然后将它们写入23.txt和24.txt的单独文本文件)

我有如下代码:

def data_extraction(inputfile):

ifile = open(inputfile, "r")
lines = ifile.readlines()


for value in lines:
each_line = value.split('\t')
service_order = each_line[0]
text = each_line[-1]

以上代码会在 for 循环内提供多个列表(value = ['23', 'Hello How are you?'] 等等)。我需要做什么才能将同一列及其对应的文本分组?

最佳答案

>>> data = """23\tHello How are you?
23\tWhat's up?
24\tI am using Python"""
>>> new_dict = defaultdict(str)
>>> data = data.split('\n')
>>> for line in data:
each_line = line.split('\t')
new_dict[int(each_line[0])] += " " + each_line[-1]

>>> print new_dict
defaultdict(<type 'str'>, {24: ' I am using Python', 23: " Hello How are you? What's up?"})

输出-

>>> for key in sorted(new_dict):
print str(key) + "\t" + new_dict[key].strip()


23 Hello How are you? What's up?
24 I am using Python

您也不应该使用 readlines 逐行读取并在读取文件时使用上下文。

with open('filename', 'r') as f:
for line in f:
# Use the above code

关于Python:基于相同元素对多个列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24819063/

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