X = ['M','W','W','M','M','W']
NUM = [1,2,3,4,5,6]
trying to write a subroutine that will take NUM list and depending on whether the value in the corresponding list is M or W will multiply the value from Num list by either 5 when M is present and 10 with W.
have tried using two target values and index numbers with little success
Something like this would do what you want:
X = ['M', 'W', 'W', 'M', 'M', 'W']
NUM = [1, 2, 3, 4, 5, 6]
X_VAL = {'M': 5,
'W': 10
}
result = []
for index, val in enumerate(NUM):
result.append(val * X_VAL[X[index]])
print(result)
Let me know if you need any help understanding the code.
EDIT: Like @user2357112 said you can zip
both lists like this:
X = ['M', 'W', 'W', 'M', 'M', 'W']
NUM = [1, 2, 3, 4, 5, 6]
X_VAL = {'M': 5,
'W': 10
}
result = []
for val, x in zip(NUM, X):
result.append(val * X_VAL[x])
print(result)
Using a simple list comprehension and Python's ternary operator:
X = ['M','W','W','M','M','W']
NUM = [1,2,3,4,5,6]
final = [i * (5 if j == 'M' else 10) for i, j in zip(NUM, X)]
print(final)
Output:
[5, 20, 30, 20, 25, 60]
If you had more than two letters, and a unique multiplication value for each one, you could use a dictionary:
>>> X = ['M','W','W','M','M','W', 'K', 'J', 'J', 'L']
>>> NUM = [1,2,3,4,5,6,4,2,1,8]
>>> dct = {'M': 5, 'W': 10, 'J': 8, 'K': 4, 'L': 3}
>>> [i * dct[j] for i, j in zip(NUM, X)]
[5, 20, 30, 20, 25, 60, 16, 16, 8, 24]
Another approach would be to use lambda
functions and map
:
def mult(x, num):
factor = lambda i: 5 if i=='M' else 10
return list(map(lambda i: factor(i[0]) * i[1],zip(x,num)))
X = ['M','W','W','M','M','W']
NUM = [1,2,3,4,5,6]
print(mult(X, NUM))
Output:
[5, 20, 30, 20, 25, 60]
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.