我有一个字符串列表,如果它存在于列表中,则要删除'',因此我将其转换为集合并执行此操作
input=set(input)
input.discard('')
input=list(input)
我可以丢弃''如果它存在,但我的设置(和列表)正在重新安排。这可以防止吗?
p.s: - 输入是我的列表,我是python的初学者。
答案 0 :(得分:2)
>>> lst = ['a', 'b', '', 'c', '', 'd']
>>> lst = [x for x in lst if x != '']
>>> lst
['a', 'b', 'c', 'd']
答案 1 :(得分:2)
使用函数式编程概念:
>>> my_list = ['hello', 'there', '', 'I', 'try', '', 'to', 'be', 'helpful']
>>> my_list = filter(lambda a: a != '', my_list)
>>> my_list
['hello', 'there', 'I', 'try', 'to', 'be', 'helpful']
我对各种答案感兴趣,所以我进行了一些比较。
import time
num_trials = 1000000
my_list = ['a', 'b', '', 'c', '', 'd']
start = time.time()
for i in xrange(num_trials):
[x for x in my_list if x != '']
end = time.time()
list_comp = (end - start) / num_trials
start = time.time()
for i in xrange(num_trials):
filter(lambda a: a != '', ['a', 'b', '', 'c', '', 'd'])
end = time.time()
functional = (end - start) / num_trials
print "Over {0} trials...".format(num_trials)
print "Using list comprehension, the average time to execute was {0}".format(list_comp)
print "Using filter and lambda, the average time to execute was {0}".format(functional)
#Over 1000000 trials...
#Using list comprehension, the average time to execute was 2.03965497017e-06
#Using filter and lambda, the average time to execute was 3.60413718224e-06
因此,列表理解似乎稍微快一些,至少对于我测试的列表而言。
编辑:我道歉!列表理解使用预分配列表my_list
,而我正在使lambda + filter表达式每次为新列表分配内存!我还对作者接受的答案filter(None, my_list)
进行了测试。该代码如下:
start = time.time()
for i in xrange(num_trials):
filter(None, my_list)
end = time.time()
filter_none = (end - start) / num_trials
新输出是:
#Over 1000000 trials...
#Using list comprehension, the average time to execute was 1.80612707138e-06
#Using filter and lambda, the average time to execute was 2.1211681366e-06
#Using filter(None), the average time to execute was 1.11886692047e-06
所以,似乎filter(None, some_list)
拿走了蛋糕!
答案 2 :(得分:1)
将列表转换为集合不会保留顺序:
list(set([3, 2, 1]))
产量
[1, 2, 3]
使用for comprehension过滤您的列表:
list = [elem for elem in list if n != unwantedElem]
答案 3 :(得分:1)
设置操作。设置操作将使您的列表元素唯一。即如果您有两次或多次相同的字符串重复多次,则将删除重复的字符串。这里应该使用列表理解。这将保留较旧的
>>> a = ['apple', 'orange', '', 'grapes', 'pineapple', '', 'cherry', '']
>>> [ x for x in a if x != '' ]
['apple', 'orange', 'grapes', 'pineapple', 'cherry']
答案 4 :(得分:1)
感谢大家,但我需要的是
filter(None, some_list)
找到它