首页 > 解决方案 > 如何合并列表的多个元素?

问题描述

在这种情况下,我有两个词(代码和问题),在它们中的每个元音之后,我想放一个特定的符号(在我的例子中,我决定使用“#”)。我设法制作了一个列表,其中在某个单词中的某个元音之后有一个符号(例如 co#de) 现在剩下的就是,我想将这些单词合并在一起。我什至决定在这里采取正确的方法吗?

我有一个包含 6 个元素的列表:

# there is "#" after every vowel in a word
lst = ["code#", "que#stion", "questi#on", "co#de", "questio#n", "qu#estion"]

我想将这些元素合并在一起,这样我就可以得到一个只有两个元素的新列表。

# the two words stay the same, but there are now multiple "#" in every word
new_lst = ["co#de#", "qu#e#sti#o#n"]

这是在 python 中甚至可以做的事情吗?

标签: pythonpython-3.x

解决方案


可以从一个新的联合国开始吗mark:)list

>>> poundit = lambda x: ''.join('{}#'.format(y) if y.lower() in ['a', 'e', 'i', 'o', 'u'] else y for y in x)
>>> lst
['code#', 'que#stion', 'questi#on', 'co#de', 'questio#n', 'qu#estion']
>>> set(poundit(x) for x in (y.replace('#', '') for y in lst))
set(['qu#e#sti#o#n', 'co#de#'])

推荐阅读