繁体   English   中英

用python中的字符串替换索引列表

[英]Replacing a list of indices with a string in python

我在列表中有一组索引:

[2 0 3 4 5]

我想用存储在另一个列表中的值替换它们:

[a b c d e f g]

并输出:

[c a d e f]

我尝试了这段代码:

for line in indices:
    print(line)
    for value in line:
        value = classes[value]
    print(line)
    break

它将两次打印原始列表。 有没有办法替换元素,还是我被迫创建一个新的列表列表?

这看起来是使用列表理解的好地方,请尝试以下方法-惯用的解决方案:

idxs  = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

[chars[i] for i in idxs]
=> ['c', 'a', 'd', 'e', 'f']

当然,我们可以按照您的预期使用显式循环执行相同的操作,但是它不像以前的解决方案那么酷:

ans = []
for i in idxs:
    value = chars[i]
    ans.append(value)

ans
=> ['c', 'a', 'd', 'e', 'f']

作为最后的选择-我不知道您为什么要在输入列表中“替换元素”(如问题所述),但是可以肯定,这也是可能的,但不建议这样做-创建起来更简单,更简洁一个带有答案的新列表(如前两个片段所示),而不是更改原始输入:

for pos, val in enumerate(idxs):
    idxs[pos] = chars[val]

idxs
=> ['c', 'a', 'd', 'e', 'f']
idxs  = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
map(lambda x : chars[x],idxs)
=> ['c', 'a', 'd', 'e', 'f']

要么

reduce(lambda x,y: x+[chars[y]],idxs,[])
=> ['c', 'a', 'd', 'e', 'f']

您还可以使用chr()函数将int转换为字符(ascii表)

>>> a = [2 0 3 4 5]
>>> [chr(i+97) for i in a]
['c', 'a', 'd', 'e', 'f']

暂无
暂无

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

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