-2

I've got a list that currently looks like this ['15 12 6', '7 20 9 10', '13 17', '3']

I want to be able to get the first number from each index (15,7,13,3), but I'm not sure how. I know how to get the first digit of each number, but I don't know what to do for the numbers with 2 digits.

JJ42
  • 17
  • 4
  • 1
    Please share what you've tried so far so that others can help accordingly :)! – Timothy Sep 16 '22 at 04:42
  • "but I don't know what to do for the numbers with 2 digits." Well, **how do you know** that they have 2 digits? How do you know that they *don't* have *more* than that? Because of the *spaces*, right? So. What if you split the string up at the whitespace? – Karl Knechtel Sep 16 '22 at 05:02

2 Answers2

0

To get the first number, you should split the string by space.

Try this:

nums = ['15 12 6', '7 20 9 10', '13 17', '3']
res = [int(x.split(' ')[0]) for x in nums] # [15, 7, 13, 3]
Jannchie
  • 690
  • 6
  • 18
0

First you'll want to get each index. As each number is split by spaces, you'll need to split the code at every space. Then you'll take the first index created by the split function.

for i in list:
    x = i.split(' ')[0]
    print(x) 
Jackie
  • 198
  • 12