[英]Pick position of a list based on the position of another list in Python
我是 Python 初學者,也是 Stackoverflow 的新手,似乎無法找到解決此問題的方法,我已經四處尋找了數周。 這是一項任務,我們不能使用內置 Python 函數。
我想找到一個項目在列表 A 中的位置,並從列表 B 中選擇相同的位置。列表 A 中的項目不應該等於零。 完成后,我必須在 B 中添加相應的值。例如:
A = [0,0,1,1]
B = [25,9,8,3]
A 應導致位置 2,3 B 因此等於 8,3 8+3 = 11
以下是我到目前為止所嘗試的
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
if binary[position] !=0:
print(position)
我想這就是你想要的。
index = 0
sums = 0
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
for value in binary:
if value == 1:
sums += decimal[index]
index += 1
print(sums)
如果您不需要這些職位,您可以使用以下內容
result = sum([y for x, y in zip(binary, decimal) if x])
在列表理解中,每對二進制、小數位將被迭代,如果二進制不為零,則只保留小數位。 然后你總結所有保留的項目。
import numpy as np
binary = np.array([0,1,1,0,0,0])
decimal = np.array([32,16,8,4,2,1])
values = np.where(binary == 1)
output_decimal = decimal[values[0]]
print(output_decimal)
這個答案通過使用 Numpy 包完成..
我想你明白了。 從您的代碼中,只需在您創建的單獨列表中注冊位置,然后將其匯總
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
if binary[position] !=0:
output_decimal.append(decimal[position])
# to add everything
print(sum(output_decimal))
輸出給你: 16+8 = 24
所以要找到列表中項目的位置並從另一個列表中選擇相同的位置,您可以非常使用循環來迭代第一個列表中的項目。 在循環內,然后檢查該項目是否不等於零,如果不是,則可以將第二個列表中的適當值添加到輸出列表。
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
# Iterate over the items in binary
for i, b in enumerate(binary):
# Check if the item is not equal to zero
if b != 0:
# If it is not, add the corresponding value in decimal to the output list
output_decimal.append(decimal[i])
# Print the output list
print(output_decimal)
所以要計算輸出列表中值的總和,您可以簡單地使用內置的 sum() 函數,如下所示:
total = sum(output_decimal)
如果你不想使用 sum 那么你可以使用下面的代碼:
total = 0
for value in output_decimal:
total += value
我認為在這種情況下使用枚舉可能是個好主意:
result = sum([B[i] for i, val in enumerate(A) if val != 0])
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.