相关疑难解决方法(0)

如何从列表列表中制作一个平面列表?

我想知道是否有一条快捷方式可以在Python列表中列出一个简单的列表.

我可以在for循环中做到这一点,但也许有一些很酷的"单行"?我用reduce尝试了,但是我收到了一个错误.

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
Run Code Online (Sandbox Code Playgroud)

错误信息

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
Run Code Online (Sandbox Code Playgroud)

python list flatten multidimensional-array

2950
推荐指数
29
解决办法
184万
查看次数

如何使用列表推导来扩展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
查看次数

在一行迭代中扩展多个元素

对于

A=[1,2,3]

我想得到

B=['r1','t1','r2','t2','r3','t3']

我知道这是很容易获得['r1','r2','r3']通过

['r'+str(k) for k in A]

如上所示,我如何通过一个线路循环获得B?

非常感谢.

python iteration loops list

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

列表理解版"延伸"

以下是否存在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
查看次数