【问题标题】:Separating a list into two - Python [duplicate]将列表分成两个 - Python [重复]
【发布时间】:2014-01-13 14:45:46
【问题描述】:

对于以下代码:

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

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

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

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

【问题讨论】:

  • 您是否知道这些列表不区分 H5NO3 和 HN5O3(比如说)?您可能希望为氮存储 1(即 N = ['5','1','3'])以获得唯一的映射。

标签: python list split alpha numeric


【解决方案1】:

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

【讨论】:

  • +0 因为你有足够的鱼可以送人;)
  • @kojiro 我尽量不回答这些问题,但有时很难抗拒。 ;-)
【解决方案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']

【讨论】:

  • 我无法确定在三元的结果上调用方法是优雅还是可怕。
  • @Wooble 除非语言保证三元的返回类型,否则这很可怕。 :P(我的两分钱。)
猜你喜欢
  • 2013-04-15
  • 2018-10-14
  • 2021-01-07
  • 2023-02-03
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
相关资源
最近更新 更多