添加到Python中的列表 - 愚蠢的分配

时间:2015-10-29 05:54:42

标签: python list append

我要创建一个程序,用以下数字填充3个列表:

  • A - 1 2 3 4 5 6 7 8 9 10
  • B - 0 2 4 6 8 10 12 14 16 18 20
  • C - 1 4 9 16 25 36 49 64 81 100

这是我到目前为止所做的:

def printList(listName):
    print(listName)
    fillerVariableForInput=input("Press any key to continue")

# Main
Alphalist=[]
for i in range(1,11):
    Alphalist.append(i)
print(Alphalist)

Bravolist=[]
for i in range(0,11):
    Bravolist.append(i*2)
print(Bravolist)

Charlielist=[]
for i in range(1,11):
    Charlielist.append(i*i)
print(Charlielist)

有更好或更有效的方法吗?我的教授坚持认为这是实现这一目标的“方式”。

3 个答案:

答案 0 :(得分:0)

是的,假设是python2:

Alphalist = range(1,11)
Bravolist = range(0,21,2)
Charlielist = [x*x for x in xrange(1,11)]

对于python3,您必须将xrange更改为range,将前两个更改为(这些也可以在python2中使用):

Alphalist = list(range(1,11))
Bravolist = list(range(0,21,2))

但是,阅读问题的“细则”可能需要您将这些数字插入现有列表或将其附加到列表中(如标题所示)。然后你可以使用extend方法:

Alphalist = []
Alphalist.extend( range(1,11) )
# etc

答案 1 :(得分:0)

在Python 3中使用它的惯用方法:

# the variable name is in snake_case and you have a space
# after each comma (see PEP8 for the full
# story about python naming conventions : https://www.python.org/dev/peps/pep-0008/)
alphalist = list(range(1, 11)) # range generate the list without a for loop
print(alphalist)

# the third parameter of range is the "step": here we count 2 by 2
bravolist = list(range(0, 21, 2))
print(bravolist)

# this is a comprehension list, a syntactic shortcut to write for loops
# building lists. It also works on dict, sets and generators.
charlielist = [i * i for i in range(1, 11)]
print(charlielist)

你的老师怎么可能希望你学习for循环的基础知识和列表的方法,在这种情况下,他给你的例子都是正确的。

在Python 2中,range()会返回list,因此您无需在其上调用list()。我建议你学习Python 3,因为版本2将在5年内消失。

答案 2 :(得分:0)

首先,我建议您查看PEP 0008 -- Style Guide for Python Code。 更具体地说:Naming Conventions

现在列表中,Python有一个很酷的东西叫做List Comprehensions。对于您的情况,我会按如下方式编写它们。

alpha_list = [i for i in range(1, 11)]
print (alpha_list)

bravo_list = [i*2 for i in range(0, 11)]
print (bravo_list)

charlie_list = [i*i for i in range(1, 11)]
print (charlie_list)