[英]Create a new list according to item value
I have a list like below.我有一个如下所示的列表。
['T46', 'T43', 'R45', 'R44', 'B46', 'B43', 'L45', 'L44', 'C46', 'C45']
where I want to group according to int value:我想根据 int 值分组的地方:
[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
I think this is what you are looking for?我想这就是你要找的?
In [1]: lst = ['T46','T43','R45','R44','B46','B43','L45','L44', 'C46', 'C45']
In [2]: [1 if x.endswith("46") else 0 for x in lst]
Out[2]: [1, 0, 0, 0, 1, 0, 0, 0, 1, 0]
In [3]: [1 if x.endswith("43") else 0 for x in lst]
Out[3]: [0, 1, 0, 0, 0, 1, 0, 0, 0, 0]
I would suggest creating a dict
and then map the values based on the integer value我建议创建一个dict
,然后根据整数值映射值
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']})
From there, you can create a list
with the areas
and then reassign the values in your dict
the area pattern从那里,您可以创建一个包含areas
的list
,然后在您的dict
重新分配区域模式中的值
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]
With itertools.groupby()
function:使用itertools.groupby()
函数:
import itertools
l = ['T46', 'T43', 'R45', 'R44', 'B46', 'B43', 'L45', 'L44', 'C46', 'C45']
coords_str = 'TRBLC' # Top, Right, Bottom, Left, Center
result = {}
for k,g in itertools.groupby(sorted(l, key=lambda x:x[1:]), key=lambda x:x[1:]):
items = list(_[0] for _ in g)
result[k] = [int(c in items) for c in coords_str]
print(result)
The output:输出:
{'44': [0, 1, 0, 1, 0], '45': [0, 1, 0, 1, 1], '43': [1, 0, 1, 0, 0], '46': [1, 0, 1, 0, 1]}
Easy to read.易于阅读。
>>> letters = {'T': 0, 'R': 1, 'B': 2, 'L': 3, 'C': 4}
>>> carlos_list = ['T46', 'T43', 'R45', 'R44', 'B46', 'B43', 'L45', 'L44', 'C46', 'C45']
>>> result = {_:5*['0'] for _ in range(43,47)}
>>> for item in carlos_list:
... list_location = letters[item[0]]
... slot = int(item[1:])
... result[slot][list_location] = '1'
...
>>> result
{43: ['1', '0', '1', '0', '0'], 44: ['0', '1', '0', '1', '0'], 45: ['0', '1', '0', '1', '1'], 46: ['1', '0', '1', '0', '1']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.