Home > Software engineering >  How to dynamically assign an unknown number of list elements?
How to dynamically assign an unknown number of list elements?

Time:06-24

I have this code which works but it's a big function block of IF..ELIF..ELSE. Is there a way to unpack or dynamically assign two lists. The thing is, sometimes mylist could have less elements than 4.

Input:

mylist=['1','2','3','4']
flag=['a','b','c','d']

Output: A string object like 'a=1/b=2/c=3/d=4/' OR 'a=1/b=2/c=3/' if mylist only has 3 elements.

My current method is just like:

def myoutput(mylist, flag):
    if flag=='3':
        out = f'a={mylist[0]}/b={mylist[1]}/c={mylist[2]}/'
    else:
        out = f'a={mylist[0]}/b={mylist[1]}/c={mylist[2]}/d={mylist[3]}/'
    return out

I tried to zip the two list, but I do not know the next steps and it doesn't really work:

tag_vars={}
for i in range((zip(mylist,flag))):
    tag_vars[f"mylist{i}"] = flag[i]

print(tag_vars)

CodePudding user response:

I would use zip for this task following way

mylist=['1','2','3','4']
flag=['a','b','c','d']
out = ''.join(f'{f}={m}/' for f,m in zip(flag,mylist))
print(out)

output

a=1/b=2/c=3/d=4/

Note that I used f,m with zip so f and m are corresponding elements from flag and mylist. Disclaimer: this solution assumes flag and mylist have always equal lengths.

CodePudding user response:

Working with a list comprehension, this solution will work for any length of mylist as long as flag has at least the same number of elements.

output = "/".join([f'{flag[i]}={mylist[i]}' for i in range(len(mylist))])   "/"

#Output
'a=1/b=2/c=3/d=4/'

Could also be :

output = "".join([f'{flag[i]}={mylist[i]}/' for i in range(len(mylist))])

CodePudding user response:

You can use zip like this:

for a, b in zip(alist, blist): ...

I modified myoutput function to return your desired output

mylist=['1','2','3','4']
flag=['a','b','c','d']

def myoutput(mylist, flag):
    result = []
    for elem, f in zip(mylist, flag):
        result.append(f"{f}={elem}")
    return "/".join(result)

print(myoutput(mylist, flag)) # a=1/b=2/c=3/d=4
print(myoutput(mylist[:3], flag)) # a=1/b=2/c=3

CodePudding user response:

You can use the enumerate like this code

   mylist=['1','2','3','4','5']
   for key,i in enumerate(mylist,start=1):
       print(f'{key} = {i}')
  • Related