相关疑难解决方法(0)

如何使用列表推导来扩展python中的列表?

我没有Python经验,我经常编写(简化)代码如下:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.append(y)
return accumulationList
Run Code Online (Sandbox Code Playgroud)

然后在我的测试通过后,我重构了

return [doSomething(x) for x in originalList]
Run Code Online (Sandbox Code Playgroud)

但是假设结果有点不同,我的循环看起来像这样:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.extend(y)
return accumulationList
Run Code Online (Sandbox Code Playgroud)

doSomething列表返回一个列表.什么是最恐怖的方式来实现这一目标?显然,之前的列表理解会给出一个列表列表.

python for-loop nested list-comprehension list

15
推荐指数
2
解决办法
5601
查看次数

Python:如何以列表理解格式扩展或附加多个元素?

我想为这段代码或类似的东西获得一个很好的整洁列表理解!

extra_indices = []
for i in range(len(indices)):
    index = indices[i]
    extra_indices.extend([index, index + 1, index +2])
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑* 索引是一个整数列表。另一个数组的索引列表。

例如,如果索引是 [1, 52, 150] 那么目标(在这里,这是我第二次想要在列表理解中对连续索引输出执行两个单独的操作)

那么 extra_indices 将是 [1, 2, 3, 52, 53, 54, 150, 151, 152]

python for-loop list-comprehension

5
推荐指数
1
解决办法
1876
查看次数

列表理解版"延伸"

以下是否存在1行等效(使用列表理解):

a = []
for i in range(6):
    a.extend(((-i,i,0,2),(-i-1,i,0,6)))
a = tuple(a)
Run Code Online (Sandbox Code Playgroud)

我在想类似的东西

tuple(((-i,i,0,2),(-i-1,i,0,6)) for i in range(6))
Run Code Online (Sandbox Code Playgroud)

但这给了:

(((0, 0, 0, 2), (-1, 0, 0, 6)),
 ((-1, 1, 0, 2), (-2, 1, 0, 6)),
 ((-2, 2, 0, 2), (-3, 2, 0, 6)),
 ((-3, 3, 0, 2), (-4, 3, 0, 6)),
 ((-4, 4, 0, 2), (-5, 4, 0, 6)),
 ((-5, 5, 0, 2), (-6, 5, 0, 6)))
Run Code Online (Sandbox Code Playgroud)

这不是我想要的.

期望的输出

((0, 0, 0, 2),
 (-1, 0, 0, 6),
 (-1, 1, 0, …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension

3
推荐指数
1
解决办法
271
查看次数

如何使用.extend list方法使用列表理解?

例如,这个片段:

out = []
for foo in foo_list:
    out.extend(get_bar_list(foo)) # get_bar_list return list with some data
return out
Run Code Online (Sandbox Code Playgroud)

如何使用列表理解来缩短此代码?

python list-comprehension

2
推荐指数
2
解决办法
590
查看次数

标签 统计

list-comprehension ×4

python ×4

for-loop ×2

list ×1

nested ×1