使用函数

时间:2017-05-19 00:34:40

标签: python list

我想知道是否有更优雅的方式来执行以下操作:

编辑:

def whaa(x):
    # Let's not get too picky about this function
    return list(range(0,x)), list(range(-1,x))

a, b = whaa(10)
c = whaa(20)
a.extend(c[0])
b.extend(c[1])

编辑:函数的行为取决于输入。我希望相应的输出整齐地放在同一个列表中。

基本上,我想要做的是访问输出元组的各个元素并扩展我的列表,而不必担心将输出存储到单独的变量中。似乎给出了这个结构,它不是可能的东西,但我愿意接受建议!

2 个答案:

答案 0 :(得分:2)

使用for循环扩展返回的元组的每个元素:

a, b = tuple(x * 2 for x in whaa())

a
# [1, 2, 3, 1, 2, 3]

b
# [2, 3, 4, 2, 3, 4]

对于更新的问题,您可以使用zip作为@John的答案:

a, b = tuple(x + y for x, y in zip(whaa(10), whaa(20)))

答案 1 :(得分:2)

你可以这样做:

for x, y in zip([a, b], c):
    x.extend(y)

但是,为什么不首先将ab放在列表中呢?

c = whaa(10)
for x, y in zip(c, whaa(20)):
    x.extend(y)
a, b = c                       # save unpacking until the end