bigly
bigly

Reputation: 5

Accessing this kind of element in list

I have a list of ["3,2", "4,5", "6,7"] and I need to write a code to compare each number of element and then do something in specific condition. a[0] will return ["3,2"]. How can I access 3 and 2 separately?

Upvotes: 0

Views: 60

Answers (2)

cl0wzed
cl0wzed

Reputation: 101

For each element in array

Element is a string. String has method split.

I split string into pieces by comma. Example:

    string = "1,2"
    result = string.split(',') # Here I split by comma
    print(result) # ['1', '2']

Python have a great mechanizm of unpacking iterable elements:

result = ['1', '2']
left, right = result
# Same as 
#    left = result[0]
#    right = result[1]

print(left)  # '1'
print(right) # '2'

# Now variables left and right store strings
# If you want to make integers:

left  = int(left)
right = int(right)
array = ["3,2", "4,5","6,7"]

for element in array:
    left_num, right_num = element.split(',')

    left_num  = int(left_num)
    right_num = int(right_num)

    print(left_num, right_num)


Upvotes: 0

andreis11
andreis11

Reputation: 1141

Let's assume this. You have a list like this:

a = ["3,2", "4,25"] 

Of course, you can reach to items like this:

print(a[0]) # 3,2
print(a[0][0]) # 3
print(a[0][2]) # 2
print(a[1][0]) # 4
print(a[1][2]) # 2

But what are you going to do if you have a two digit number? You split the string by comma.

print(a[0].split(',')[0]) #3
print(a[0].split(',')[1]) #2
print(a[1].split(',')[0]) #4
print(a[1].split(',')[1]) #25

Then, when you compare them, don't forget to transform the string (3 or 2) into numbers (integers) so you can compare them. This is called casting.

for element in a:
  if int(element.split(',')[0]) > int(element.split(',')[1]):
    print('first is bigger')
  else:
    print('second is bigger')

Upvotes: 1

Related Questions