输入:
我有一个文件,在每个换行符中有数千个长度相同的字符串(如上面所列的5个字符)。以下是该文件中每个字符串的属性,
目标/预期产出:
输入/输出
Input
abc**M**1
abc**L**1
aef**L**2
aef**K**3
Output
M L K
abcM1 abcL1 -
- aefL2 -
- - aefK3我被建议使用迭代工具中的"groupby“函数,这有助于根据”第4“字符对字符串进行分组。但是,我确信不能像上面的输出那样以所需的格式打印这些列表。
发布于 2017-02-06 13:39:14
这可能不是最短的答案,但应该相当容易读懂。
主要目标是构建条目的2d地图:
下面是一个示例,您可以根据需要更新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 发布于 2017-02-06 12:59:07
首先必须使用sorted函数根据第5个索引对列表进行排序,然后根据第5个索引调用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 - aefK3https://stackoverflow.com/questions/42068209
复制相似问题