Can a list comprehension be used instead of the for loop below?
shod_l = list() # Initialize a list for empty pd.DataFrames that will be used later for merging of api query results
for q in range(len(shod_list)): #shod_list is a list containing several strings
q = pd.DataFrame()
shod_l.append(q)
You can use list comprehension like this (since your assignment inside the loop has no effect):
shod_l = [pd.DataFrame() for _ in range(len(shod_list))]
All you need to do is:
shod_l = [pd.DataFrame() for _ in shod_list]
or if using a variable q
:
shod_l = [pd.DataFrame() for q in shod_list]
or if you're determined to use a range:
shod_l = [pd.DataFrame() for q in range(len(shod_list))]
To answer the title question, yes, it's possible using assignment expressions . The equivalent loop would be
shod_l = [q := pd.DataFrame() for _ in range(len(shod_list))]
but as mentioned in the other answers, there's no point to binding q
, so in this particular case, the assignment isn't needed.
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.