Home > database >  I have problem with my loop list. cant get the expected result
I have problem with my loop list. cant get the expected result

Time:06-01

here's my code :

UserList = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]
ListStrUser = []

for ListStrUser in UserList:
   ListStrUser = GetNum(UserList)

def GetNum(anyList):                     
    for i in range(1,len(anyList)):         
        anyList[i] = re.sub (r'\D',"", str(anyList[i]))
    return anyList

print(ListStrUser)

######## expected result :

[['person1', '25','70','170'],[ 'person2','21','54','164']]

CodePudding user response:

You were not far off Asif. But I cannot add much more to Ethan's answer which is why I'm confused that it was down voted. If you want a function that can handle all the work without the need for another for loop then this function below will do just that:

import re

UserList = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]

def get_num(any_list):
    # includes the for loop to iterate through the list of lists
    list_str_user = []
    for inner_list in any_list:
        temp_list = [inner_list[0]]
        for i in range(1,len(inner_list)):
            temp_list.append(re.sub(r'\D', '', str(inner_list[i])))
        list_str_user.append(temp_list)
    return list_str_user

print(get_num(UserList))

Output:

[['person1', '25', '70', '170'], ['person2', '21', '54', '164']]

So no need for the for loop outside the function.

CodePudding user response:

from @Guy 's comment:

UserList = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]

import re
def GetNum(anyList):
    for i in range(1,len(anyList)):
        anyList[i] = re.sub (r'\D',"", str(anyList[i]))
    return anyList
ListStrUser = []
for ListStr in UserList:
   ListStrUser.append(GetNum(ListStr))


print(ListStrUser)

gives

[['person1', '25', '70', '170'], ['person2', '21', '54', '164']]

CodePudding user response:

Try the following code:

user_list = [['person1', '25yo','70kg','170cm'],[ 'person2','21yo','54kg','164cm']]
list_str_user = []


def get_num(any_list):     
    updated_list = [any_list[0]]

    for i in range(1,len(any_list)):         
        updated_list.append(re.sub(r'\D',"", str(any_list[i])))
    
    return updated_list


for user in user_list:
    list_str_user.append(get_num(user))

print(list_str_user)

Notice I also updated the naming of your variables and functions and the spacing between functions to be compliant with pep8. Keep this in mind when writing Python code.

Also functions should be defined before you use them otherwise Python won't find them.

I also created the updated_list variable in get_num, it's never a bad idea to not mutate parameters in functions.

  • Related