2017-10-11 47 views
-1

我有一個像下面這樣的列表。根據項目值創建一個新列表

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

該列表中的項目如何與您的組示例相關聯? –

+0

哦..所以這兩個數字是組,然後第一個字符是標誌... gotcha –

回答

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] 
+0

如何獲得'區域[0]'?在'[(鍵,區域)鍵',area_pattern.items()]''中的區域 –

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] 
+0

我會從你的想法開始,是否有可能實現模式'區域模式[頂部,右部,底部,左,中心]' –

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]} 
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']} 
相關問題