简体   繁体   中英

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

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')

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.

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]

使用列表理解:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM