2011-07-09 46 views
0

我试图从一个字符串添加全字到另一个它们是否包含某个字符:的Python:添加从StringList的一个词到另一个StringList的

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

为什么store ='word'?如果你不改变它,只需在代码中使用单词。 – utdemir

+0

我认为,如果我没有,'字'将被更新到一个字符列表,当它被检查'h' – tetris11

+0

不,它不会。 'in'只是对它进行迭代,而不改变它。 – utdemir

回答

7

使用append[docs]

newlist.append(store) 

或更短(使用list comprehension[docs]):

newlist = [word for word in mylist if 'h' in word] 

为什么newlist += store不行?

这是一样的newlist = newlist + store延长现有列表(在左侧)所有在sequence[docs]右侧的项目。如果按照文件,你会发现这一点:

s + ts的级联和t

在Python,不仅名单序列,但字符串是太(字符序列)。这意味着序列中的每个项目(→每个字符)都会附加到列表中。

+0

真棒。进一步证明Python是最怪异和最出色的语言之一。 – tetris11

+1

请使用列表理解。不成熟的优化是不成熟的,最好的方法可能会根据字符串的数量/大小而有所不同。此外,它更加Pythonic。不要试图告诉Python如何做事,只是要求它给你想要的东西。现在是2011年。我们的高级语言现在运行良好。 –

+0

@Karl Knechtel,@eryksun - 根据''timeit''列表理解是最快的(在我的电脑上)。我把我的代码和结果放在一个答案中。 – Blair

0

尝试使用:

newlist.append(store) 
0

用于表达这一点的另一个替代语法是使用filter。因此,对于你的问题的实现看起来像

filt = lambda x: 'h' in x 
newlist1 = filter(filt, mylist) 
+0

请注意,这是有效的,但使用“timeit”显示它比Felix Kling的答案中的列表理解慢大约2.5倍。 – Blair

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 

结果
  1. 列表理解在2.92us
  2. 环路在4.32us(比列表解析慢48%)
  3. 筛选呼叫在7.23us(比列表理解较慢148%)
+0

非常好!谢谢你 – tetris11

相关问题