将列表分成两部分 - Python

Jas*_*078 0 python split alpha list numeric

对于以下代码:

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

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

n = ['5' , '3']
c = ['H' , 'N' , 'O']
Run Code Online (Sandbox Code Playgroud)

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

Ash*_*ary 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']
Run Code Online (Sandbox Code Playgroud)

  • +0因为你有足够的鱼可以把它们送走;) (4认同)