以下代码:
print("Welcome to the Atomic Weight Calculator.")
compound = input("Enter compund: ")
compound = H5NO3
lCompound = list(compound)
我想从列表lCompund
创建两个列表。我想要一个字符列表和另一个数字列表。所以我可能会有这样的事情:
n = ['5' , '3']
c = ['H' , 'N' , 'O']
有人可以提供简单的解决方案吗?
答案 0 :(得分:6)
使用列表理解并使用str.isdigit
和str.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']