0

For the following code:

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

I want to create two lists from the list lCompund. I want one list for characters and the other for digits. So that I may have something looking like this:

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

Can somebody please help by providing a simple solution?

mdml
  • 22,442
  • 8
  • 58
  • 66
Jasmine078
  • 389
  • 2
  • 4
  • 16
  • Are you aware that those lists don't distinguish between H5NO3 and HN5O3 (say)? You might want to store a 1 for the nitrogen (i.e. N = ['5','1','3']) to get a unique mapping. – starsplusplus Jan 14 '14 at 13:48

2 Answers2

6

Use a list comprehension and filter items using str.isdigit and 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']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

Iterate the actual string only once and if the current character is a digit, then store it in the numbers otherwise in the chars.

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

Output

['5', '3'] ['H', 'N', 'O']
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    I can't decide if calling a method on the result of a ternary is elegant or horrifying. – Wooble Jan 13 '14 at 15:04
  • @Wooble It's horrifying unless the language guarantees the return type of the ternary. :P (My two cents.) – kojiro Jan 13 '14 at 18:20