简体   繁体   中英

Leave parts of the instructions blank for python to complete

I'm new to Python so I don't know if this is possible, but my guess is yes. I want to iterate over a list and put items into new lists according to their value. For instance, if item_x == 4 , I would want to put it in a list called list_for_4 . The same is true for all other items in my list and numbers 0 to 10. So is it possible to generalize a statement in such a way that if item_x == *a certain value* , it will be appended to list_for_*a certain value* ? Thanks!

Maybe use list comprehension with if statement inside?

Like:

list_for_4 = [x for x in my_list if x==4]

And combine it with a dict.

Instead of trying to generate a dynamic variables. A map using a dictionary structure might help you.

For example:

from collections import defaultdict
item_list = [1, 2, 3, 9, 2, 2, 3, 4, 4]

# Use a dictionary which elements are a list by default:
items_map = defaultdict(list)

for i in item_list:
    items_map['list_for_{}'.format(i)].append(i)
print(items_map)

#  Test the map for elements in the list:
if 'list_for_4' in items_map:
    print(items_map['list_for_4'])
else:
    print('`list_for_4` not found.')

Alternatively if you only require the number of times an item occurs in the list you could aggregate it using Counter :

from collections import Counter
item_list = [1, 2, 3, 9, 2, 2, 3, 4, 4]
result = Counter(item_list)
print(result)

With a simple iteration through the list:

lst_for_1 = []
lst_for_2 = []
lst_for_3 = []
d = {1: lst_for_1, 2: lst_for_2, 3: lst_for_3}
for x in lst:
    d[x].append(x)

Or, if you want a condition that is more complicated than just the value of x, define a function:

def f(x):
  if some condition...:
     return lst_for_1
  elif some other condition:
     return lst_for_2
  else:
     return lst_for_3

Then replace d[x].append(x) by f(x).append(x) .

If you don't want to do the iteration yourself, you could also use map:

list(map(lambda x: d[x].append(x),lst))

or

list(map(lambda x: f(x).append(x),lst))

The version with map will return an list of Nones that you don't care about. map(...) returns an iterator, and as long as you do not iterate through it (for example, to turn its result into a list), it will not perform the mapping. That's why you need the list(map(...)) , it will create a dummy list but append the items of lst to the right lists on the way, which is what you want.

Don't know why you want to do it. But you can do it.

data = [1, 2, 3, 4, 1, 2, 3, 5]

for item in data:
    name = f'list_for_{item}'
    if name in globals():
        globals()[name].append(item)
    else:
        globals()[name] = [item]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM