gpt4 book ai didi

python - 使用副本创建不同的文本文件

转载 作者:行者123 更新时间:2023-11-28 17:46:56 24 4
gpt4 key购买 nike

我正在努力从另一个文本文件创建一个文本文件。

我的文本文件是:

0.0 99.13 0.11
0.5 19.67 0.59
0.5 22.23 1.22
1.0 9.67 0.08

我想创建一个文本文件,例如:

0.0 99.13 0.11
0.5 19.67 0.59
1.0 9.67 0.08

0.0 99.13 0.11
0.5 22.23 1.22
1.0 9.67 0.08

通常,每当我的文件的第一列中出现重复值时,我都想创建一个只包含一个重复值和所选行的值的文件。

到目前为止我的代码是:

def createFile(file):
with open(file, 'r') as fh:
data = fh.read()
for row in data.splitlines():
column = row.split()
print column
>>>
['0.0', '99.13', '0.11']
['0.5', '19.67', '0.59']
['0.5', '22.23', '1.22']
['1.0', '9.67', '0.08']

哪个可以让我玩索引 - 也许检查 column[0] 是否重复然后打印该行?或者创建字典会更容易吗?

干杯,凯特

最佳答案

如果重复项按顺序分组,使用itertools.groupby :

from itertools import groupby

data = """0.0 99.13 0.11
0.5 19.67 0.59
0.5 22.23 1.22
1.0 9.67 0.08""".split('\n')

result = [list(j) for i, j in groupby(data, lambda x: x.split(' ', 1)[0])]

files_num = 0
for e in result:
files_num = max(files_num, len(e))

for i in range(files_num):
with open('{}.txt'.format(i), 'w+') as f:
for line in result:
min_index = min(i, len(line)-1)
f.write('{}\n'.format(line[min_index]))

0.txt:

0.0 99.13 0.11
0.5 19.67 0.59
1.0 9.67 0.08

1.txt:

0.0 99.13 0.11
0.5 22.23 1.22
1.0 9.67 0.08

否则,如果它们没有按顺序分组,您可以使用 collections.OrderedDict这样(像 1_CR suggested ,但有一些变化):

from collections import OrderedDict

data = """0.0 99.13 0.11
0.5 19.67 0.59
1.0 9.67 0.08
0.5 22.23 1.22""".split('\n')

d = OrderedDict()
for line in data:
split = line.split(' ', 1)
d.setdefault(split[0], []).extend(split[1:])

print(d)

输出:

OrderedDict([ ('0.0', ['99.13 0.11']), 
('0.5', ['19.67 0.59', '22.23 1.22']),
('1.0', ['9.67 0.08']) ])

关于python - 使用副本创建不同的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16835231/

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