Lycon
Lycon

Reputation: 2499

How can i append a an item only if it meets certain rules in python

i would like to append an item into list_b only if it is one above '5H' which is '6H'

list_a = ('2A','4A','8H','6H')
list_b = ['5H']

list_a.pop() gives a '6H' therefore if i append the '6H' it should be able to be added to list_b since its just one above '5H'.

i tried to compare the first values but it gives an error because the 1 in the code below is an int and list_b[-1][0] is a str.

if list_b[-1][0] + 1 != list_a.pop()[0]:
    print('Error')

Therefore i cannot use list_b[-1][0] + 1

Upvotes: 0

Views: 121

Answers (4)

Lev Levitsky
Lev Levitsky

Reputation: 65811

First off, your list_a is a tuple, not a list. Check the parentheses.

If

list_a = ['2A','4A','8H','6H']
list_b = ['5H']

you can do something like:

while list_a:
    t = list_a.pop()
    if int(t[0]) == int(list_b[-1][0]) + 1:
        list_b.append(t)
    else:
        print 'Error'

to process the elements of list_a iteratively.

Upvotes: 0

Joel Cornett
Joel Cornett

Reputation: 24788

Use a list comprehension:

list_b.extend([i for i in list_a if int(i[0]) == (int(list_b[-1][0]) + 1)])

Upvotes: 0

John Machin
John Machin

Reputation: 82992

Presuming that list_a really is a list, not a tuple, otherwise list_a.pop() won't work ...

You need to do TWO things:

(1) convert the first characters to int so that you can compare them properly
(2) check that the second characters are the same ... from your problem description, it would appear that '6G' and '6I' (amongst many others) are not OK

b_value = list_b[-1]
a_value = list_a.pop()

ok = int(b_value[0]) + 1 == int(a_value[0]) and b_value[1] == a_value[1]

Upvotes: 0

Reinstate Monica
Reinstate Monica

Reputation: 4723

It should suffice to turn the character into the integer it represents by using int:

if int(list_b[-1][0]) + 1 != int(list_a.pop()[0]):
    print('Error')

Upvotes: 1

Related Questions