微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在python中输入动态列表

如何解决如何在python中输入动态列表

1 ) input: 3,return [1,2,3]
then continue 
2) input: 2,return [2,4,3]
then continue 
3) input: 6,return [3,6,5,6]
then continue 
4) input: 1,return [4,6]
then continue 
5) input: 1,return [5,6]

我的代码

1)

list_num = [ int(i) for i in input('enter numbers divided by space ').split()]

print(list_num)
lst = []

# number of elemetns as input
n = int(input("Enter number of elements : "))
 
# iterating till the range
for i in range(0,n):
    ele = int(input())
 
    lst.append(ele) # adding the element
     
print(lst)

test_list1 = []
n2 = int(input("Enter number of elements2 : "))

for i2 in range(0,n2):
    ele2 = int(input())
 
    test_list1.append(ele2) # adding the element

print(test_list1)

res_list = [lst[i] + test_list1[i2] for i in range(len(lst))]

print(res_list)

但不是动态的

解决方法

您的代码 2 似乎在进行成对列表添加。
但是您的 res_list 的计算使用的是 i2 索引,它应该只是 i

没有修复:[4,5] 加上 [0,1] 给出 [5,6]
修复后:[4,5][0,1] 给出 [4,6]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。