如果我有任意顺序的卡套装列表,如下所示:
suits = ["h", "c", "d", "s"]
Run Code Online (Sandbox Code Playgroud)
我想要返回一个没有的列表 'c'
noclubs = ["h", "d", "s"]
Run Code Online (Sandbox Code Playgroud)
有一个简单的方法来做到这一点?
ava*_*sal 41
suits = ["h","c", "d", "s"]
noclubs = [x for x in suits if x != "c"]
Run Code Online (Sandbox Code Playgroud)
jam*_*lak 39
>>> suits = ["h","c", "d", "s"]
>>> noclubs = list(suits)
>>> noclubs.remove("c")
>>> noclubs
['h', 'd', 's']
Run Code Online (Sandbox Code Playgroud)
如果你不需要单独的 noclubs
>>> suits = ["h","c", "d", "s"]
>>> suits.remove("c")
Run Code Online (Sandbox Code Playgroud)
alu*_*ach 24
这个问题已得到解答,但我想解决使用列表理解比使用慢得多的评论.remove().
我机器上的一些配置文件(使用Python 2.7.6).
%%timeit
x = ['a', 'b', 'c', 'd']
y = x[:] # fastest way to copy
y.remove('c')
1000000 loops, best of 3: 405 ns per loop
%%timeit
x = ['a', 'b', 'c', 'd']
y = list(x) # not as fast copy
y.remove('c')
1000000 loops, best of 3: 689 ns per loop
%%timeit
x = ['a', 'b', 'c', 'd']
y = [n for n in x if n != 'c'] # list comprehension
1000000 loops, best of 3: 544 ns per loop
%%timeit
x = ['a', 'b', 'c', 'd']
i = x.index('c')
y = x[:i] + x[i + 1:]
1000000 loops, best of 3: 656 ns per loop
Run Code Online (Sandbox Code Playgroud)
如果您使用最快的方式复制列表(不太可读),您将比使用列表解析快36%.但是如果你使用list()类复制列表(这是更常见的和Pythonic),那么你将比使用列表理解慢26%.
真的,这一切都很快.我认为可以做出.remove()比列出列表理解技术更具可读性的论点,但除非你有兴趣放弃复制中的可读性,否则它不一定更快.
列表理解在这种情况下的最大优点是它更简洁(即如果你有一个函数是出于某种原因从给定列表中删除一个元素,它可以在一行中完成,而另一种方法需要3行.)有时候单行可以非常方便(虽然它们通常以牺牲一些可读性为代价).此外,如果您实际上并不知道要删除的元素是否实际位于列表中,那么使用列表推导会很好.虽然.remove()将抛出一个ValueError,列表理解将按预期运行.
您可以使用过滤器(或来自 itertools 的 ifilter)
suits = ["h","c", "d", "s"]
noclubs = filter(lambda i: i!='c', suits)
Run Code Online (Sandbox Code Playgroud)
您还可以使用列表构造进行过滤
suits = ["h","c", "d", "s"]
noclubs = [ i for i in suits if i!='c' ]
Run Code Online (Sandbox Code Playgroud)
小智 5
如果为了不打紧,一组操作可用于:
suits = ["h", "c", "d", "s"]
noclubs = list(set(suits) - set(["c"]))
# note no order guarantee, the following is the result here:
# noclubs -> ['h', 's', 'd']
Run Code Online (Sandbox Code Playgroud)
不使用 for 循环或 lambda 函数并保留顺序:
suits = ["h","c", "d", "s"]
noclubs = suits[:suits.index("c")]+suits[suits.index("c")+1:]
Run Code Online (Sandbox Code Playgroud)
我知道在内部它仍然会使用循环,但至少您不必在外部使用它们。