我想在单子上加几个字。如果我执行for循环,则返回的答案是正确的。
然而,如果我进行一个列表理解方法,我没有得到任何答案。我做错了什么?
x=[]
for i in range(0,10):
x.append('hi'+str(i))
print(x)答:['hi0', 'hi1', 'hi2', 'hi3', 'hi4', 'hi5', 'hi6', 'hi7', 'hi8', 'hi9']
x= [x.append('hi'+str(i)) for i in range(0,10)]
print(x)答:[None, None, None, None, None, None, None, None, None, None]
发布于 2021-05-17 15:21:59
您不需要使用append,因为您在列表中,而append在所有情况下都不返回任何内容。
x= ['hi'+str(i) for i in range(0,10)]
print(x)发布于 2021-05-17 15:22:28
您的x = [x.append('hi'+str(i)) for i in range(0,10)],构建一个列表,其中包含每个x.append调用的结果,即None,就像在内部完成的那样,然后使用该新列表擦除x。
你想要的
x = [f"hi{i}" for i in range(10)]https://stackoverflow.com/questions/67572495
复制相似问题