【问题标题】:Is there a better way to sum an element to a list of different length?有没有更好的方法将一个元素加到一个不同长度的列表中?
【发布时间】:2021-09-17 06:39:10
【问题描述】:

有没有更好的方法来做到这一点?也许使用 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]



【问题讨论】:

  • 104 和 204 是从哪里来的?
  • @ronpi 抱歉,我有一个错字,我已经对其进行了编辑以进行更改。预期输出应为 [101, 102, 103, 201, 202, 203]

标签: python list loops tuples add


【解决方案1】:

列表理解:

>>> [x + y for x in main_tx for y in add_tx]
[101, 102, 103, 104, 201, 202, 203, 204]
>>> 

【讨论】:

    【解决方案2】:

    是的,您绝对可以使用 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)
    

    现在,您可以使用列表推导更高效、更 Python 化:

    tx = [x + user_x for x, user_x in product(main_tx, add_tx)]
    

    另外,正如 @don't talk just code 在 cmets 中提到的,您也可以这样做:

    tx = list(map(sum, product(main_tx, add_tx)))
    

    这可能是实现结果的最有效方式

    【讨论】:

    • 谢谢你的回答,这很有用。所以如果我有一个 ty 列表,我会这样做吗? tx = [x + user_x for x, user_x in product(main_tx, add_tx)]ty = [y + user_y for y, user_y in product(main_ty, add_ty)]list(product(tx, ty)) # get all combination
    • 是的,您也可以使用main_tyadd_ty 创建ty 列表,方法与您提到的相同。更准确地说,这些不完全是组合,而是元素的cartesian product。您还有一个 combinations 函数,它接受一个可迭代对象和一个大小 (int),并从可迭代对象返回指定大小的所有可能元素组合。
    • 呸,当你说product时,我原以为这会以tx = list(map(sum, product(main_tx, add_tx)))结束...
    • 另外,如果有帮助,您可以接受答案,或者您认为合适的最佳答案。
    猜你喜欢
    • 2021-12-16
    • 2021-09-05
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多