是否有更好的方法來做到這一點?也許可以用itertools或operator,或其他什么方法?
我目前是這樣做的。
我目前是這樣做的。
main_tx = [100, 200]
add_tx = [1, 2, 3]
tx = []
for x in main_tx:
for user_x in add_tx:
t = x user_x
tx.append(t)
print(tx) #[101, 102, 103, 201, 202, 203]/span>
uj5u.com熱心網友回復:
一個串列的理解:
>>> [x y for x in main_tx for y in add_tx]
[101, 102, 103, 104, 201, 202, 203, 204]
>>>
uj5u.com熱心網友回復:
是的,你肯定可以使用itertools及其product函式,它可以迭代給定迭代物(在你的例子中是兩個list物件)的笛卡爾積:
from itertools import product
main_tx = [100, 200]
add_tx = [1, 2, 3]
tx = []
for x, user_x in product(main_tx, add_tx)。
tx.append(x user_x)
現在,你可以用串列理解的方式更有效、更pythonic地完成這個任務:
tx = [x user_x for x, user_x in product(main_tx, add_tx)]
另外,正如@don't talk just code的評論中提到的,你也可以這樣做:
tx = list(map(sum, product( main_tx, add_tx))
這可能是實作結果的最有效的方法
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/327365.html
標籤:
