我试图将一个字符串中的整个单词添加到另一个字符串中,如果它们包含某个字符:
mylist = ["hahah", "hen","cool", "breaker", "when"]
newlist = []
for word in mylist:
store = word #stores current string
if 'h' in word: #splits string into characters and searches for 'h'
newlist += store #adds whole string to list
print newlist
我期望的结果是:
newlist = ["hahah","hen","when"]
但我得到了:
newlist = ['h', 'a', 'h', 'a', 'h', 'h', 'e', 'n', 'w', 'h', 'e', 'n']
如何获得预期结果?
答案 0 :(得分:7)
newlist.append(store)
或更短(使用list comprehension [docs]):
newlist = [word for word in mylist if 'h' in word]
为什么newlist += store
不起作用?
这与newlist = newlist + store
相同,并且通过右侧sequence [docs]中的所有项目扩展现有列表(左侧)。如果您按照文档进行操作,您会发现:
的串联
s + t
s
和t
在Python中,不仅列表是序列,而且字符串也是(字符序列)。这意味着序列中的每个项目(→每个字符)都会附加到列表中。
答案 1 :(得分:1)
出于兴趣,我决定看看三个解决方案中的哪一个(循环,列表理解和filter()
函数)是最快的。对于任何感兴趣的人,我的测试代码和结果如下。
>>> import timeit
>>> num_runs = 100000
>>> setup_statement = 'mylist = ["hahah", "hen","cool", "breaker", "when"]'
>>> loop_statement = """
newlist = []
for word in mylist:
if 'h' in word:
newlist.append(word)"""
>>> timeit.timeit(loop_statement, setup_statement, number=num_runs) / num_runs
4.3187308311462406e-06
>>> list_statement = "newlist = [word for word in mylist if 'h' in word]"
>>> timeit.timeit(list_statement, setup_statement, number=num_runs) / num_runs
2.9228806495666502e-06
>>> filter_statement = """
filt = lambda x: "h" in x
newlist = filter(filt, mylist)"""
>>> timeit.timeit(filter_statement, setup_statement, number=num_runs) / num_runs
7.2317290306091313e-06
答案 2 :(得分:0)
尝试使用:
newlist.append(store)
答案 3 :(得分:0)
另一种表达方式是使用filter
。因此,您的问题的实现看起来像
filt = lambda x: 'h' in x
newlist1 = filter(filt, mylist)