根据项目值创建新列表

2024-06-12 10:40:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单如下

  ['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

Tags: inrightidfortoparealeftcenter
3条回答

使用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]}

我想这就是你要找的

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]

我建议创建一个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']})

从那里,您可以用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]

相关问题 更多 >