Is it possible to convert a loop like this into a list comprehension?
lst_a = []
lst_b = []
lst_c = []
test_dict = {'a':1, 'b':2, 'c':3, 'd':4}
for k, v in test_dict.items():
lst_a.append(k)
lst_b.append(k.upper())
lst_c.append((k+k))
For example, to something like this:
lst_a, lst_b, lst_c = [list comprehension logic here for the above loop]
Note: The output must be three separate lists like the one in the loop.
Try it with zip()
:
test_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
lst_a, lst_b, lst_c = zip(*[(k, k.upper(), k+k) for k in test_dict])
# Convert them to list
# lst_a, lst_b, lst_c = map(list, zip(*[(k, k.upper(), k+k) for k in test_dict)]))
# Iterate this dict three times.
# lst_a, lst_b, lst_c = ([k for k in test_dict], [k.upper() for k in test_dict], [k + k for k in test_dict])
print(lst_a,lst_b,lst_c)
lst_a = []
lst_b = []
lst_c = []
test_dict = {'a':1, 'b':2, 'c':3, 'd':4}
[[lst_a.append(k), lst_b.append(k.upper()), lst_c.append(k+k)] for k in test_dict]
print(lst_a, lst_b, lst_c)
output - ['a', 'b', 'c', 'd'] ['A', 'B', 'C', 'D'] ['aa', 'bb', 'cc', 'dd']
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.