Skip to content Skip to sidebar Skip to footer

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: [id][' ',' ',' ',' ',' ']

Solution 1:

I think this is what you are looking for?

In [1]: lst =  ['T46','T43','R45','R44','B46','B43','L45','L44', 'C46', 'C45']

In [2]: [1if x.endswith("46") else0forxin lst]
Out[2]: [1, 0, 0, 0, 1, 0, 0, 0, 1, 0]

In [3]: [1if x.endswith("43") else0forxin lst]
Out[3]: [0, 1, 0, 0, 0, 1, 0, 0, 0, 0]

Solution 2:

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']})

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: [1if l in v else0for 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]

Solution 3:

With itertools.groupby() function:

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

Solution 4:

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 _ inrange(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']}

Post a Comment for "Create A New List According To Item Value"