Использование 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')
Остальной код остается прежним