Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表分为两部分_Python_List_Split_Alpha_Numeric - Fatal编程技术网

Python 将列表分为两部分

Python 将列表分为两部分,python,list,split,alpha,numeric,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'] 有人能提供一个简单的解决方案吗?使用

对于以下代码:

print("Welcome to the Atomic Weight Calculator.")
compound = input("Enter compund: ")
compound = H5NO3
lCompound = list(compound)
我想从列表
lCompund
中创建两个列表。我想要一个字符列表,另一个数字列表。这样我就可以得到这样的东西:

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

有人能提供一个简单的解决方案吗?

使用列表理解,并使用
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']

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

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

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

+0,因为您有足够的鱼可以将其送出;)@我尽量不回答这样的问题,但有时很难抗拒我无法决定对三元结果调用方法是优雅的还是可怕的。@Wooble这很可怕,除非语言保证三元的返回类型:P(我的两分钱)你知道这些清单没有区分H5NO3和HN5O3(比如说)?您可能希望为氮存储一个1(即N=['5'、'1'、'3']),以获得唯一的映射。