Python 列出给定代码的理解
Python list comprehension for the given code
我可以使用列表理解或减少代码的 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)
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]
我可以使用列表理解或减少代码的 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)
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]