简体   繁体   中英

Conditional statements in List comprehension with nested lists(Python 3):

elements = ['121', '9', '55', '5']

I am trying to check if any of the items in elements list is a palindromic number. If there exists any, return True(else False). I tried implementing by using map + lambda: here is the snippet,

print(any(map(lambda x: (all(map(lambda y: x[y] == x[-y-1], range(int(len(x)/2))))), elements )))

but I couldn't implement the same idea using list comprehension technique. Can someone please, suggest me with it. Here is what i did:

print(any([True if x[y] == x[-y-1] for y in (range(int(len/2)) for x in elements)]))

You still have to use an all(..) otherwise you will return True from the moment one character is palindromic in a string:

any([x[y] == x[-y-1] for y in range(len//2)) for x in elements])

Or you can decide to omit the all(..) , and work with slices :

any([x[:len(x)//2] == x[:len(x)//2-1:-1] for x in elements])

We do not need to stop at len(x)//2 and use a substring for the reverse: we might decide to compare x with x[::-1] but since our strings are half as long, the comparison will take less long.

Furthermore you better use // for integer division: it will floor the result.

That being said using any without the list comprehension will usually be faster : by using list comprehension you force Python to first evaluate all the elements and check if these are a palindrom. Then you are going to check whether one was. By using a generator, Python will stop from the moment it has found a single palindrome, not looking whether the other elements are palindromes.

This checks whether the number in a list is a palindrome or not.
This includes a function and an iterable.

def palindrome(n):
    x1 = list(str(n))
    x2 = x1[::-1]
    if x1 == x2 :
        return True
    else:
        return False

elements ['121','9','55', '5']
list = [palindrome(int(n)) for n in elements]

I've implemented lambda functions to define both sides:

elements = ['121', '9', '55', '5', '123']

count_to_middle = lambda x: len(x) // 2

left_side = lambda x: list(x[:count_to_middle(x)])
right_side = lambda x: list(reversed(x))[:count_to_middle(x)]

array = [left_side(var) == right_side(var) for var in elements]

print array
# >>> [True, True, True, True, False]

print all(array)
# >>> False

print any(array)
# >>> True

This should help.

In your code line:

print(any([True if x[y] == x[-y-1] for y in (range(int(len/2)) for x in elements)]))

You use range(int(len/2)) without specifying it ( len(of_so.nething) )

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