'assignments between loops be expressed as python comprehension
Can the case of multiple ifs (like switch) or assignments between for loops be expressed as python comprehension (list comprehension) or any simplification?
The following three examples:
1.This function wants to insert the string into the list A
A= ["apple", 'banana', 'cat', 'duck', ...'n']
for i in [7, 3, 2, 1]:
if i == 1:
A.insert(i, A[i])
if i == 2 or i == 1:
A.insert(i, A[i])
A.insert(i, A[i])
The following two formulas want to do the function of word count:
2.
B= ["apple", 'banana', 'cat', 'duck', ...'n']
C = set(B)
dic = {}
for a in C:
value = 0
for wordCount in B:
if a == wordCount:
value = value + 1
dic[a] = value
word_sorted = sorted(dic.keys())
values = list(dic.values())
value_sorted = []
for k in word_sorted:
i = 0
for k1 in dic.keys():
if k == k1 :
value_sorted.append(values[i])
i = i + 1
Solution 1:[1]
For the second example, if the goal is to count the amount of element in the array, you can do it with dictionnary comprehension like this :
arr = ["apple", "banana", "cat", "duck", "duck"]
dic = { word: arr.count(word) for word in set(arr) }
print(dic) # {'apple': 1, 'banana': 1, 'cat': 1, 'duck': 2}
On the third example, if the goal is to get the values of the dict sorted by the keys, you can use list comprenhension :
dic = {'apple': 1, 'banana': 1, 'cat': 1, 'duck': 2}
sorted_values =[dic[key] for key in sorted(dic.keys())]
print(sorted_values) # [2, 1, 1, 2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukas Laudrain |
