[英]Grouping and formatting of the list based on nth character
輸入:
我有一個文件,其中每個換行符中都有數千個相同長度的字符串(上面列出的5個字符)。 以下是該文件中每個字符串的屬性,
目標/期望的輸出:
例如:輸入/輸出
Input
abc**M**1
abc**L**1
aef**L**2
aef**K**3
Output
M L K
abcM1 abcL1 -
- aefL2 -
- - aefK3
建議我使用itertools中的“ groupby”函數,該函數有助於根據“第4個”字符對字符串進行分組。 但是我確定不能像上面的輸出中那樣以所需的格式打印這些列表。
您將必須首先使用sorted
函數基於5th索引對列表進行sorted
,然后必須基於5th索引調用itertools.groupby
(使用operator.itemgetter
來實現)。 例如:
>>> from operator import itemgetter
>>> from itertools import groupby
>>> my_list = ['abc**M**1', 'abc**L**1', 'aef**L**2', 'aef**K**3', 'xyz**M**3']
>>> [[i.replace('*', '') for i in j] for _, j in groupby(sorted(my_list, key=itemgetter(5)), key=itemgetter(5))]
[['aefK3'], ['abcL1', 'aefL2'], ['abcM1', 'xyzM3']]
# ^ ^ ^
# K-Group L-Group M-Group
根據問題中提到的示例,您的列表似乎已被排序。 在這種情況下,您可以跳過排序部分。
現在每個組都有籃子。 為了用空-
填充它。 您可以通過以下方式創建一個for循環:
# same value extracted from above code
group_basket = [['aefK3'], ['abcL1', 'aefL2'], ['abcM1', 'xyzM3']]
depth = 3
for b in group_basket:
for i in range(depth):
if i >= len(b) or not b[i].endswith(str(i+1)):
b.insert(i, '-')
group_basket
持有的最終價值將是:
>>> group_basket
[['-', '-', 'aefK3'],
['abcL1', 'aefL2', '-'],
['abcM1', '-', 'xyzM3']]
您可以使用zip
以以下所需格式打印數據:
for x in zip(*group_basket[::-1]):
print('\t'.join(x))
# which prints:
# --------------------
# abcM1 abcL1 -
# - aefL2 -
# xyzM3 - aefK3
這可能不是最短的答案,但通俗易懂。
主要目標是構建條目的二維地圖:
這是示例,您可以根據需要更新print_entries
:
inputs = ['abcM1', 'abcL1', 'aefL2', 'aefK3']
def parse_inputs(inputs):
entries = dict() # key (abc,1), key ['M', 'L', 'K']
for input_string in inputs:
# parse and break down
version = input_string[3]
unique_id = int(input_string[4])
key = (input_string[:3], unique_id)
# put in ditionary
if key not in entries:
entries[key] = dict()
entries[key][version] = input_string
return entries
def print_entries(entries):
ids = ['M', 'L', 'K']
print '{:^6} {:^6} {:^6}'.format(*ids)
for key in sorted(entries.keys()):
cur_entries = entries[key]
# for each id, find the entry, if not found, use placeholder '_'
outputs = [cur_entries[_id] if _id in cur_entries else '_' for _id in ids]
print '{:^6} {:^6} {:^6}'.format(*outputs)
entries = parse_inputs(inputs)
print_entries(entries)
輸出為:
M L K
abcM1 abcL1 _
_ aefL2 _
_ _ aefK3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.