【问题标题】:Removing vowels from a list of strings [duplicate]从字符串列表中删除元音[重复]
【发布时间】:2020-01-15 04:55:08
【问题描述】:

我有一个包含 5 个元素的列表(我们称之为“列表”):

['sympathize.', 'sufficient.', 'delightful.', 'contrasted.', 'unsatiable']

我想从列表的每个项目删除 元音 (vowels = ('a', 'e', 'i', 'o', 'u')),最终结果应该是这样

没有元音的列表:

['sympthz.', 'sffcnt.', 'dlghtfl.', 'cntrstd.', 'nstbl']

有什么想法吗?提前致谢。

我的代码:

list = ['sympathize.', 'sufficient.', 'delightful.', 'contrasted.','unsatiable']
     vowels = ('a', 'e', 'i', 'o', 'u')
        for x in list.lower():
            if x in vowels:
                words = list.replace(x,"")

输出:

AttributeError: 'list' object has no attribute 'lower'

【问题讨论】:

  • 嗯,list没有lower属性,可以调用x.lower()
  • 不要使用名称list,因为它是 Python 中的内置类型。
  • words = ['sympathize.', 'sufficient.', 'delightful.', 'contrasted.','unsatiable'] vowels = ('a', 'e', 'i', 'o', 'u') for x in words.lower(): if x in vowels: words = words.replace(x,"")
  • 我得到了同样的错误(for x in words.lower(): AttributeError: 'list' object has no attribute 'lower')

标签: python list element


【解决方案1】:

这是使用str.maketrans的一种方式:

l = ['sympathize.', 'sufficient.', 'delightful.', 'contrasted.', 'unsatiable']

table = str.maketrans('', '', 'aeiou')

[s.translate(table) for s in l]
# ['sympthz.', 'sffcnt.', 'dlghtfl.', 'cntrstd.', 'nstbl']

【讨论】:

  • 这也是个好方法,谢谢补充!
【解决方案2】:

试试这个:

mylist = ['sympathize.', 'sufficient.', 'delightful.', 'contrasted.','unsatiable']
vowels = ['a', 'e', 'i', 'o', 'u']
for i in range(len(mylist)):
    for v in vowels:
        mylist[i] = mylist[i].replace(v,"")
print(mylist)

【讨论】:

  • 谢谢,它可以正常工作。
猜你喜欢
  • 2014-06-04
  • 2018-08-27
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 2013-07-07
  • 2019-10-16
相关资源
最近更新 更多