简体   繁体   中英

Multiple if and for loop in list comprehension

I am facing issue while converting my below code in list comprehension

A = {
  "name": ['sahil', 'pankaj', 'honey'],
  'test': 'data'
}

Mylist = []
for k, v in A.items():
    if isinstance(v, list):
        for i in v:
            Mylist.append(i)
    else:
        Mylist.append(v)

I tried this code via list comprehension but failed to get the result

Mylist = [i
  for k, v in A.items() if isinstance(v, list) for i in v
  else i = v
]

I am facing issue syntax error.

since you know that key 'name' holds a list and the key 'test' holds a string you can use:

Mylist = [e for e in [*A['name'], A['test']]]

and more simple:

Mylist = [*A['name'], A['test']]

in the above line, you are creating a list using the unpacking operator and your string element

output:

['sahil', 'pankaj', 'honey', 'data']

or if you do not want wnat to use the dict keys you can use:

Mylist = [i for e in A.values()  for i in (e if isinstance(e, list) else [e])]

You could use the keys() method of the dict structure to get the values into a list. Hope this helps too

  A = {
    "name": ['sahil', 'pankaj', 'honey'],
    "test": 'data'
  }

 Mylist = []
 for k in A.keys():
    if k == "name":
       Mylist.extend(A[k]) #using extend as we already have a list present in the value for the dict, this just concatenates into one main list
    else:
       Mylist.append(A[k])
 print(Mylist)

OR just using a list comprehension:

   A = {
    "name": ['sahil', 'pankaj', 'honey'],
    "test": 'data'
   }
   Mylist = [v for (k,v) in A.items() if k == "name"] #only returns values for k equal to "name"

   print(Mylist)

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