繁体   English   中英

如何合并列表的多个元素?

[英]How to merge multiple elements of a list?

在这种情况下,我有两个词(代码和问题),在其中的每个元音之后,我想放一个符号(在我的情况下,我决定使用“#”)。 我设法制作了一个列表,其中我在单词中的某个元音之后有一个符号(例如 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中甚至可以做到吗?

可以从一个新的未mark ed 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#'])

遍历每个单词的每个字母,用旧单词生成一个新单词,找到元音时附加一个“#”

words = ['code', 'question']
vowels = ['a', 'e', 'i', 'o', 'u']
new_words = []
#Iterate through words
for word in words:
    new_word = ''
    #Iterate through letters
    for letter in word:
        new_word+= letter
        #Add a # when you find a vowel
        if letter in vowels:
            new_word+='#'
    new_words.append(new_word)
print(new_words)
#['co#de#', 'qu#e#sti#o#n']
new_words = []
for word in words:
    temp_word = ""
    for element in word:
        if element not in vowels:
            temp_word += element
        else:
            temp_word += element
            temp_word += "#"
    new_words.append(temp_word)

使用正则表达式来做到这一点

import re
lst = ["code#", "que#stion", "questi#on", "co#de", "questio#n", "qu#estion"]

def func(x):
   o = ''
   for c in x:
       o += c
       if c.lower() in 'aeiou':
           o += '#'
   return o

x = list(map(func, set(map(lambda x: re.sub('#', '', x), lst))))
print(x)

Out: ['co#de#', 'qu#e#sti#o#n']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM