转换字符列表中的元素

时间:2014-05-05 12:01:14

标签: python

列表是

l=[i for i in range(65,91)]

当且仅当元素可被2整除时,我想将元素转换为其对应的char。

输出为, ['B','D','F','H','J','L','N','P','R','T','V','X',' Z']

希望输出为,

[65, 'B', 67, 'D', 69, 'F'...]

如何使用list comphrension进行此操作?

我的代码是。

>>>  l=[chr(i) for i in range(65,91)]
>>> new=[chr(i) for i in l if i%2==0]
>>> new
['B', 'D', 'F', 'H', 'J', 'L', 'N', 'P', 'R', 'T', 'V', 'X', 'Z']

2 个答案:

答案 0 :(得分:3)

>>> L = [i for i in range(65, 91)]  # or just L = range(65, 91)
>>> L[1::2] = [chr(x) for x in L[1::2]]
>>> L
[65, 'B', 67, 'D', 69, 'F', 71, 'H', 73, 'J', 75, 'L', 77, 'N', 79, 'P', 81, 'R', 83, 'T', 85, 'V', 87, 'X', 89, 'Z']

答案 1 :(得分:1)

只需将您的代码修改为:

new = [chr(i) if i%2==0 else i for i in range(65,91)]    #you don't even need the l list anymore

>>> print new
[65, 'B', 67, 'D', 69, 'F', 71, 'H', 73, 'J', 75, 'L', 77, 'N', 79, 'P', 81, 'R', 83, 'T', 85, 'V', 87, 'X', 89, 'Z']