Home > Back-end >  Assign values for objects inside a list comprehension
Assign values for objects inside a list comprehension

Time:08-18

Having a list and list of objects Eg:

new_price = [20.00, 30.00, 45.00...]
item_list = [obj1, obj2, obj3...]

Trying to do something like this

[x.price = y for x, y in zip(item_list, new_price)]

Now, the x & y is not detected as parameters. Thanks for the help

CodePudding user response:

A list comprehension is a convenient way to create a list. It's not intended to be used in the way you are suggesing.

See here: https://docs.python.org/3/glossary.html#term-list-comprehension

A compact way to process all or part of the elements in a sequence and return a list with the results. result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] generates a list of strings containing even hex numbers (0x..) in the range from 0 to 255. The if clause is optional. If omitted, all elements in range(256) are processed.

I would suggest you use a for loop. It's clean, simple, and quite frankly, more readable than a list comprehension would be anyway.

In [1]: from dataclasses import dataclass

In [2]: @dataclass
   ...: class Item:
   ...:     price: int
   ...:

In [3]: new_price = [20.00, 30.00, 45.00]

In [4]: a = Item(99)

In [5]: b = Item(98)

In [6]: c = Item(97)

In [7]: item_list = [a, b, c]

In [8]: for x, y in zip(item_list, new_price):
    ...:     x.price = y
    ...:

In [9]: a
Out[9]: Item(price=20.0)

In [10]: b
Out[10]: Item(price=30.0)

In [11]: c
Out[11]: Item(price=45.0)

CodePudding user response:

Simply:

new_price = [20.00, 30.00, 45.00...]
item_list = [obj1, obj2, obj3...]

n = min([len(new_price),len(item_list)])

for i in range(n):
    item_list[i].price=new_price[i]

  • Related