【问题标题】:Append the value of several variables into a list at the same time [duplicate]同时将多个变量的值附加到列表中[重复]
【发布时间】:2016-03-10 20:24:12
【问题描述】:

例如:

name   =       raw_input('Enter Part Name: ')
numid  = int(  raw_input('Enter NumId: '))
height = float(raw_input('Enter Height (in feet): '))
length = int(  raw_input('Enter Length: '))

现在我想将它们附加到一个名为 NewInput 的列表中 我必须写四行吗?喜欢:

NewIput=[]
NewInput.append(name)
NewInput.append(numid)

还有更简单的方法吗?

【问题讨论】:

  • 不,你可以使用list.extend
  • NewIput = [name, numid, height, length]

标签: python


【解决方案1】:

既然你从一个空列表开始,为什么不直接使用这个:

NewInput = [name, numdid, height, length]

如果您有一个已经有条目的列表,那么您可以使用+= 运算符,因为列表是可变的。例如:

NewInput += [name, numdid, height, length]

顺便说一句,在这种情况下,您可能需要考虑使用字典而不是列表。我假设您有一个用例来查询一些有用信息的用途。为什么不以更易于理解和可用的方式存储它。例如字典:

new_input= {
    'name' = raw_input('Enter Part Name: '),  # raw_input --> input for Python 3
    'numid' = int(raw_input('Enter NumId: ')),
    'height' = float(raw_input('Enter Height (in feet): ')),
    'length' = int(raw_input('Enter Length: '))
}

【讨论】:

    【解决方案2】:

    你可以使用list1.extend(list2)

    NewInput.extend([name, Numid])
    

    性能和可读性上的差异很小,所以我认为它不会有太大的不同。

    【讨论】:

    • 哦!谢谢!它有效!
    猜你喜欢
    • 2013-12-23
    • 2014-12-09
    • 2013-01-29
    • 2021-02-23
    • 2021-04-23
    • 1970-01-01
    • 2022-08-19
    • 2012-10-05
    • 2021-11-14
    相关资源
    最近更新 更多