1

使用 Python,我希望能够将多个值/元素/项目添加到单个列表中,而不必重复 .append 方法

这是我的意思的一个例子。查看以下 Python 函数:

singleList = []

def cal(rock):
    singleList.append(rock)
    singleList.append(input('Size: '))
    singleList.append(int(input('Qty: ')))
    print(singleList)

rock = cal(input('Rock: '))

Rock: granite
Size: small
Qty: 2

['granite', 'small', 2]

--singleList.append(list_element) -- 语句每次都必须重复。是否不可能做更多这样的事情:

singleList = []

def cal(rock):
    singleList.append(rock), input('Size: '), int(input('Quantity: '))
    print(singleList)

rock = cal(input('Rock: '))

...最终还是:

['granite', 'small', 2]

我尝试这样做的每一种方式,我都会收到以下错误。

TypeError: append() 只接受一个参数(给定 3 个)

我知道 .append() 根据错误消息只能接受一个参数。有没有其他方法可以解决这个问题,还是人们只是为每个参数/元素/值/项目重复 .append() 语句?

PS有人知道正确的术语:参数/元素/值/项目吗?

4

3 回答 3

3

你可以做

singleList.extend(
                 [rock, input('Size: '), int(input('Quantity: '))]
                 )

或等效地

singleList += [rock, input('Size: '), int(input('Quantity :'))]

singleList = singleList + <other list>这是Python+使用该方法解释的语法糖,如果您有兴趣__iadd__,可以在此处找到更多详细信息。正如评论中所指出的,这将使列表发生变化,因此您不能直接在printorreturn语句中使用它。

于 2018-08-17T21:15:46.910 回答
1

您主要有两个选择:

1)使用extend

singleList.extend([rock, input('Size: '), int(input('Quantity: '))])

2)将您的列表与另一个列表连接起来:

singleList += [rock, input('Size: '), int(input('Quantity: '))]

它们的性能非常接近:

$ python -m timeit 'l = [1,2,3]; l.extend([4,5,6,7,8,9])'
1000000 loops, best of 3: 0.553 usec per loop

$ python -m timeit 'l = [1,2,3]; l += [4,5,6,7,8,9]'
1000000 loops, best of 3: 0.493 usec per loop
于 2018-08-17T21:28:42.237 回答
0
singleList.extend(
    [rock, input('Size: '), int(input('Quantity: '))]
)
于 2018-08-17T21:15:51.067 回答