小编CFW*_*CFW的帖子

如何缩短多个IF .... IN ... OR语句?

如何缩短以下MWE?

files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if '.jpg' in x or '.png' in x or '.JPG' in x]
print images
Run Code Online (Sandbox Code Playgroud)

我在思考

files = ['a.txt', 'b.jpg', 'c.png', 'd.JPG', 'e.JPG']
images = [x for x in files if ('.jpg' or '.png' or '.JPG') in x]
print images
Run Code Online (Sandbox Code Playgroud)

这不起作用.

与这篇文章相反:检查文件扩展名,我也对一个概括感兴趣,它不关注文件结尾.

python if-statement list python-2.7

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

在Python中附加到zip()

给定任意数量的压缩列表,例如

>>> L1 = [1,2,3]
>>> L2 = [1,2,3]
>>> zipped = zip(L1, L2)
[[(1, 1), (2, 2), (3, 3)]
Run Code Online (Sandbox Code Playgroud)

如何将另一个列表附加到zipped,生成相同的输出

>>> L3 = [5,5,5]
>>> zip(L1, L2, L3)
[(1, 1, 5), (2, 2, 5), (3, 3, 5)]
Run Code Online (Sandbox Code Playgroud)

我正在考虑append()的方向,但这会产生以下不希望的结果

>>> zipped.append(L3)
[(1, 1), (2, 2), (3, 3), [5, 5, 5]]
Run Code Online (Sandbox Code Playgroud)

背景:我想在循环中为任意数量的列表创建压缩列表.

编辑:

现在我觉得我错过了问题的一部分.这是一个基于RyE的MWE答案:

import random

N = 4
zipped2 = zip([1,2,3],[1,2,3])  # works
zipped2 = []  # does not work
for n in range(N):
    Ln = random.sample(xrange(100),3)
    zipped2 = [old …
Run Code Online (Sandbox Code Playgroud)

python append

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

标签 统计

python ×2

append ×1

if-statement ×1

list ×1

python-2.7 ×1