Python - 迭代和更改列表的元素

Python - iterate and change elements of a list

我刚开始学习 python,在迭代和 if 语句方面遇到问题。

我有一个列表d:

d = ['s','u','p','e','r','c','a','l','i','f','r','a','g','i','l','i','s','t','i','c','e','x','p','i','a','l','i','d','o','c','i','o','u','s']

我需要遍历列表并检查每个元素是否等于元音(a, e, i, o, u).如果它是一个元音字母,那么该元素必须替换为一个子列表,该子列表在该字母之前包含单词 'vowel'。例如,如果检测到 'a',它将被替换为 ['vowel', 'a']

虽然我知道这是不正确的,但到目前为止我已经想到了:

for items in d:
    if items == 'a':
        d[items:items] = ['vowel', 'a']

要检查成员资格,您可以使用 in 操作数,对于替换,您可以使用 enumerate 遍历列表:

>>> for i,item in enumerate(d) :
...   if item in ('a', 'e', 'i', 'o', 'u') :
...              d[i]=['vowel',item]
... 
>>> d
['s', ['vowel', 'u'], 'p', ['vowel', 'e'], 'r', 'c', ['vowel', 'a'], 'l', ['vowel', 'i'], 'f', 'r', ['vowel', 'a'], 'g', ['vowel', 'i'], 'l', ['vowel', 'i'], 's', 't', ['vowel', 'i'], 'c', ['vowel', 'e'], 'x', 'p', ['vowel', 'i'], ['vowel', 'a'], 'l', ['vowel', 'i'], 'd', ['vowel', 'o'], 'c', ['vowel', 'i'], ['vowel', 'o'], ['vowel', 'u'], 's']
>>> 

您已经很接近了,这是所需的最少编辑。

for items in d:
    if items in {'a', 'e', 'i', 'o', 'u'}:
        d[d.index(items)] = ['vowel', items]   # Get the index of the element, then replace 
print(d)

您可以使用列表理解:

[['vowel', i] if i in 'aeiou' else i for i in d]

试试看:

for key, l in enumerate(d):
    if l in ('a', 'e', 'i', 'o', 'u'):
        d[key] = ['vowel', l]

在长度范围内迭代要便宜得多。您可以避免元素查找,这将花费您额外的 0(n).

for index in xrange(len(d)):
    if d[index] in 'aeiou':
        d[index] = ['vowel', d[index]]