相关疑难解决方法(0)

Python:根据条件拆分列表?

从美学角度和绩效角度来看,根据条件将项目列表拆分为多个列表的最佳方法是什么?相当于:

good = [x for x in mylist if x in goodvals]
bad  = [x for x in mylist if x not in goodvals]
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方式来做到这一点?

更新:这是实际的用例,以便更好地解释我正在尝试做的事情:

# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims  = [f for f in files if f[2].lower() not in IMAGE_TYPES]
Run Code Online (Sandbox Code Playgroud)

python

245
推荐指数
14
解决办法
14万
查看次数

如何在列表推导中使用重新匹配对象

我有一个函数从字符串列表中挑出块并将它们作为另一个列表返回:

def filterPick(lines,regex):
    result = []
    for l in lines:
        match = re.search(regex,l)
        if match:
            result += [match.group(1)]
    return result
Run Code Online (Sandbox Code Playgroud)

有没有办法将其重新表述为列表理解?显然它是相当清楚的; 只是好奇.


感谢那些贡献的人,特别提到了@Alex.这是我最终得到的浓缩版本; 正则表达式匹配方法作为"预先提升"参数传递给filterPick:

import re

def filterPick(list,filter):
    return [ ( l, m.group(1) ) for l in list for m in (filter(l),) if m]

theList = ["foo", "bar", "baz", "qurx", "bother"]
searchRegex = re.compile('(a|r$)').search
x = filterPick(theList,searchRegex)

>> [('bar', 'a'), ('baz', 'a'), ('bother', 'r')]
Run Code Online (Sandbox Code Playgroud)

python regex list-comprehension

41
推荐指数
4
解决办法
7万
查看次数

按功能排序python列表

我有一个函数,它将一个对象作为参数并给我一个数字.我希望使用这个数字作为排序列表的关键.

如果我要遍历列表,我会做类似的事情:

sorted_list = []
for object in my_list_of_objects:
    i = my_number_giving_function(object)
    sorted_list.insert(i, object)
Run Code Online (Sandbox Code Playgroud)

我如何才能sorted获得相同的结果,是否可取?这是我想出来的,但我不知道该怎么把'???'

sorted_list = sorted(my_list_of_objects, key=my_number_giving_function(???))
Run Code Online (Sandbox Code Playgroud)

python sorting list

27
推荐指数
1
解决办法
4万
查看次数

标签 统计

python ×3

list ×1

list-comprehension ×1

regex ×1

sorting ×1