简体   繁体   中英

how can i compare string within a list to an integer number?

my task today is to create a function which takes a list of string and an integer number. If the string within the list is larger then the integer value it is then discarded and deleted from the list. This is what i have so far:

def main(L,n):

    i=0
    while i<(len(L)):
        if L[i]>n:
            L.pop(i)
        else:
            i=i+1
    return L

    #MAIN PROGRAM
    L = ["bob", "dave", "buddy", "tujour"]
    n = int (input("enter an integer value)
    main(L,n)

So really what im trying to do here is to let the user enter a number to then be compared to the list of string values. For example, if the user enters in the number 3 then dave, buddy, and tujour will then be deleted from the list leaving only bob to be printed at the end.

Thanks a million!

Looks like you are doing to much here. Just return a list comprehension that makes use of the appropriate conditional.

def main(L,n):
    return([x for x in L if len(x) <= n])

You should not remove elements from a list you are iterating over, you need to copy or use reversed :

L = ["bob", "dave", "buddy", "tujour"]
n = int(input("enter an integer value"))

for name in reversed(L):
    # compare length of name vs n
    if len(name) > n:
        # remove name if length is > n
        L.remove(ele)
print(L)

Making a copy using [:] syntax:

   for name in l[:]:
        # compare length of name vs n
        if len(name) > n:
            # remove name if length is > n
            L.remove(ele)
    print(L)

只需使用内置的filter方法,其中n是截止长度:

newList = filter(lambda i:len(i) <= n, oldList)

This is a simple solution where you can print L after calling the main function. Hope this helps.

def main(L,n): l=len(L) x=0 while x<l: #if length is greater than n, remove the element and decrease the list size by 1 if len(L[x])>n: L.remove(L[x]) l=l-1 #else move to the next element in the list else: x=x+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