我有一个如下列表。
['T46', 'T43', 'R45', 'R44', 'B46', 'B43', 'L45', 'L44', 'C46', 'C45']
我想根据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
这可能吗?我到目前为止尝试的是:
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
答案 0 :(得分:1)
我认为这就是你要找的东西?
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]
答案 1 :(得分:0)
我建议创建一个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']})
从那里,您可以使用list
创建areas
,然后重新分配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]
答案 2 :(得分:0)
使用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)
输出:
{'44': [0, 1, 0, 1, 0], '45': [0, 1, 0, 1, 1], '43': [1, 0, 1, 0, 0], '46': [1, 0, 1, 0, 1]}
答案 3 :(得分:0)
易于阅读。
>>> 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']}