如何在python中的列表中动态插入数据

时间:2014-05-29 03:02:24

标签: c python-2.7

用C编写的以下代码的python等效代码:

int a[100];
int lim;
scanf("%d",&lim)
for(i=0;i<lim;i++)
    scanf("%d",&a[i]);

2 个答案:

答案 0 :(得分:2)

这里

# create an empty list
a = [];
# take limt as input
lim = raw_input("Enter limit")

# this is python style of for loop
# here i will start from 0 and will go upto limit
for i in range (0, int(lim)):
    # take input from user one by one and append to list
    elem = raw_input("")
    a.append(int(elem))

答案 1 :(得分:0)

这相当于:

lim = int(raw_input("Enter the limit: ")
a = [int(raw_input()) for i in range(lim)]

这将整数输入作为我们想要的输入数量,然后使用列表推导将它们添加到列表中。