【问题标题】:Adding to Lists in Python - Silly assignment在 Python 中添加到列表 - 愚蠢的分配
【发布时间】:2016-01-29 03:52:27
【问题描述】:

我要创建一个程序,用以下数字填充 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)

有没有更好或更有效的方法来做到这一点?我的教授坚持认为这是做到这一点的“最佳”方式。

【问题讨论】:

  • Charlielist = [i*i for i in range(1,11)]一样使用list comprehension
  • 好吧,他错了:列表推导更简洁,对于这类事情,更具可读性。

标签: python list append


【解决方案1】:

是的,假设是 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

【讨论】:

    【解决方案2】:

    在 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 年内消失。

    【讨论】:

      【解决方案3】:

      首先,我建议您查看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)
      

      【讨论】:

        猜你喜欢
        • 2019-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-26
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多