Python:将一个字符串列表中的单词添加到另一个字符串列表中

0 投票
4 回答
6105 浏览
提问于 2025-04-16 21:11

我想把一个字符串中的完整单词添加到另一个字符串中,前提是这些单词里包含某个特定的字符:

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']

我该怎么做才能得到我想要的结果呢?

4 个回答

0

试着使用:

newlist.append(store)
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.92微秒
  2. 循环耗时4.32微秒,比列表推导慢了48%
  3. 过滤调用耗时7.23微秒,比列表推导慢了148%
7

使用 append [文档] 方法:

newlist.append(store)

或者可以更简洁一点(使用 列表推导 [文档]):

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

为什么 newlist += store 不起作用?

这其实和 newlist = newlist + store 是一样的,都是在把右边的所有元素添加到左边的现有列表中。如果你查看文档,你会发现:

s + tst 的连接

在 Python 中,不仅列表是序列,字符串也是(字符串是字符的序列)。这意味着序列中的每一个元素(→ 每一个字符)都会被添加到列表中。

撰写回答