将列表分成两部分 - Python

时间:2014-01-13 14:45:46

标签: python list split alpha numeric

以下代码:

print("Welcome to the Atomic Weight Calculator.")
compound = input("Enter compund: ")
compound = H5NO3
lCompound = list(compound)

我想从列表lCompund创建两个列表。我想要一个字符列表和另一个数字列表。所以我可能会有这样的事情:

n = ['5' , '3']
c = ['H' , 'N' , 'O']

有人可以提供简单的解决方案吗?

2 个答案:

答案 0 :(得分:6)

使用列表理解并使用str.isdigitstr.isalpha过滤项目:

>>> compound = "H5NO3"
>>> [c for c in compound if c.isdigit()]
['5', '3']
>>> [c for c in compound if c.isalpha()]
['H', 'N', 'O']

答案 1 :(得分:2)

仅迭代实际字符串一次,如果当前字符是数字,则将其存储在numbers中,否则存储在chars中。

compound, numbers, chars = "H5NO3", [], []
for char in compound:
    (numbers if char.isdigit() else chars).append(char)
print numbers, chars

<强>输出

['5', '3'] ['H', 'N', 'O']