【问题标题】:Python list comprehension for the given code给定代码的 Python 列表理解
【发布时间】:2020-08-29 16:57:19
【问题描述】:

我可以使用列表解析或减少代码的 for 循环吗?

x=[100,200,300]
y=[10,20,50,70,80]
results=[]
for i in range(len(x)):
    temp=[]
    for j in range(len(y)):
        x[i]+=y[j]
        temp.append(x[i])
    results.append(temp)
print(results)

【问题讨论】:

  • x 未在您共享的 sn-p 中定义。
  • 对不起先生,我现在加了x!

标签: python list-comprehension nested-loops


【解决方案1】:

Python 3.8 添加了 assignment expressions 的简洁功能,它在生成累积和时非常方便,并且可以帮助您在几个列表推导中替换这些循环:

total = 0
cumsums = [total := total + t for t in y]
result = [[c+s for c in cumsums]  for s in x]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2019-02-07
    • 2019-06-20
    相关资源
    最近更新 更多