2014-01-13 63 views
0

对于下面的代码:分离列表分为两个 - Python的

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

您是否知道这些名单并不H5NO3和HN5O3之间(比方说)区分?您可能想要为氮保存1(即N = ['5','1','3'])以获得唯一的映射。 – starsplusplus

回答

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'] 
+4

+0因为你有足够的鱼可以给他们; – kojiro

+0

@kojiro我尽量不回答这样的问题,但有时很难抵挡。 ;-) –

2

迭代的实际字符串只有一次,如果当前的字符是一个数字,然后将其保存,否则在numberschars

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

输出

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

我不能决定是否调用一个三元结果的方法是优雅或可怕的。 – geoffspear

+0

@Wooble除非语言保证三元组的返回类型,否则这很可怕。 :P(我的两分钱) – kojiro