[英]Efficient way to parse different lines of a text file
我有一個包含如下數據的文本文件:
1 --- 1 --- 100
2 --- 1 --- 200
3 --- 1 --- 100
1 --- 2 --- 300
2 --- 2 --- 100
3 --- 2 --- 400
我想提取對應於第二列不同值的第三列數據,例如在第三列中添加與第二列中的數字1對應的三個數字,依此類推。 我可以逐行循環遍歷文本,並在每行中找到第三列並添加它們。 但這不是我想要的。 我應該如何在 Python 中有效地做到這一點?
使用itertools.groupby()
。
例如,我正在使用您的確切“數據結構” (stackoverflow 問題中的一堆文本):
import itertools
data_structure = '''
1 --- 1 --- 100
2 --- 1 --- 200
3 --- 1 --- 100
1 --- 2 --- 300
2 --- 2 --- 100
3 --- 2 --- 400
'''.splitlines()
# create a key function able to extract the data you want to group:
def _key(line):
return line.strip().split(' --- ')[1] # the 1 here means second column
#cleanup data:
clean_data = (line.strip() for line in data_structure if line.strip())
# then pass it to itertools.groupby:
for key, lines in itertools.groupby(clean_data, key=_key):
print("Lines that contain number", key, 'in second column:')
print(', '.join(lines))
結果:
Lines that contain number 1 in second column:
1 --- 1 --- 100, 2 --- 1 --- 200, 3 --- 1 --- 100
Lines that contain number 2 in second column:
1 --- 2 --- 300, 2 --- 2 --- 100, 3 --- 2 --- 400
編輯:既然你編輯了問題,並說你有一個文本文件,那么你可以用它代替data_structure
,它會起作用:
data_structure = open('myfile.txt')
其余代碼保持不變
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.