根据项目值创建一个新列表 [英] Create a new list according to item value
本文介绍了根据项目值创建一个新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下列表.
['T46', 'T43', 'R45', 'R44', 'B46', 'B43', 'L45', 'L44', 'C46', 'C45']
我要根据int值分组的地方:
where I want to group according to int value:
[id][' ',' ',' ',' ',' '] # AREA PATTERN [Top, Right, Bottom, Left, Center]
[46]['1','0','1','0','1'] #Top,Bottom,Center
[45]['0','1','0','1','1'] #Right,Left,Center
[43]['1','0','1','0','0'] #Top,Bottom
[44]['0','1','0','1','0'] #Right,Left
这可能吗?到目前为止,我尝试过的是:
Is this possible? What I tried so far is:
id_area = []
for a in area:
id = a[1:3]
areas = a[:1]
if any(str(id) in s for s in area):
id_area = #lost
推荐答案
我建议创建一个dict
,然后根据整数值映射值
I would suggest creating a dict
and then map the values based on the integer value
from collections import defaultdict
mapping = defaultdict(list)
items = ['T46', 'T43', 'R45', 'R44', 'B46', 'B43', 'L45', 'L44', 'C46', 'C45']
for i in items:
mapping[int(i[1:])].append(i[0])
print(mapping)
>>> defaultdict(<class 'list'>, {43: ['T', 'B'], 44: ['R', 'L'], 45: ['R', 'L', 'C'], 46: ['T', 'B', 'C']})
从那里,您可以用areas
创建一个list
,然后在dict
区域模式中重新分配值
From there, you can create a list
with the areas
and then reassign the values in your dict
the area pattern
areas = ['T', 'L', 'B', 'R', 'C']
area_pattern = {k: [1 if l in v else 0 for l in areas] for k, v in mapping.items()}
for key, areas in area_pattern.items():
print(key, areas)
>>> 43 [1, 0, 1, 0, 0]
>>> 44 [0, 1, 0, 1, 0]
>>> 45 [0, 1, 0, 1, 1]
>>> 46 [1, 0, 1, 0, 1]
这篇关于根据项目值创建一个新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文