簡體   English   中英

為列表推導中的對象賦值

[英]Assign values for objects inside a list comprehension

有一個對象列表和列表例如:

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

試圖做這樣的事情

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

現在,x & y 沒有被檢測為參數。 謝謝您的幫助

列表推導式是創建列表的便捷方式。 它不打算以您建議的方式使用。

見這里:https://docs.python.org/3/glossary.html#term-list-comprehension

一種處理序列中所有或部分元素並返回包含結果的列表的緊湊方法。 result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] 生成包含偶數十六進制數 (0x..) 的字符串列表,范圍從 0 到255. if 子句是可選的。 如果省略,則處理 range(256) 中的所有元素。

我建議你使用for循環。 它干凈、簡單,坦率地說,它比列表理解更易讀。

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)

簡單地:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM