簡體   English   中英

具有多個 if 語句的列表理解

[英]list comprehension with multiple if statements

我有 4 個列表,我想要一個最終列表,其中包含所有列表的每個索引的最大值以及它所屬的列表如果它來自第一個列表,我標記為 'a',依此類推...但我有一個列表理解問題。有一個我找不到的語法:

import numpy as np

a=np.array([[1,200],[4,5]])
b=np.array([[11,33],[65,666]])
c=np.array([[1,2040],[54,522]])
d=np.array([[1,3],[685,222]])


x,y=a.shape

m=[]

for i in np.arange(x):
  for j in np.arange(x):
    maximum=max ( a[i][j] ,b[i][j],c[i][j] ,d[i][j])
    m.append ((maximum,['a' if maximum in a  else 'b'  if maximum in b  else 'c'  if maximum in c else 'd'  if maximum in d ]  ))
  

我的列表理解錯誤在哪里?

這是創建理解列表的一般規則

[expression for item in iterable if condition == True]

在您的情況下,您完全缺少可迭代的。 另外,您的條件不正確。

我假設您想獲取每列的最大值列表以及該值所在列表的名稱。 在這種情況下,您可以使用該理解列表:

m.append((maximum,[name for lis, name in ((a, 'a'), (b, 'b'), (c, 'c'), (d, 'd')) if maximum in lis]))

NumPy 數組不僅僅是嵌套列表。 例如,您可以輕松地將四個數組收集到一個 3d 數組中:

import numpy as np

a = np.array([[1,200], [4,5]])
b = np.array([[11,33], [65,666]])
c = np.array([[1,2040], [54,522]])
d = np.array([[1,3], [685,222]])

abcd = np.stack([a, b, c, d])
abcd.shape
(4, 2, 2)

現在可以非常方便地獲得原始數組上每個索引對的最大值:

np.max(abcd, axis=0)
array([[  11, 2040],
       [ 685,  666]])

要獲取每個最大數字來自哪個列表的索引號,您可以使用np.argmax

np.argmax(abcd, axis=0)
array([[1, 2],
       [3, 1]], dtype=int64)

在這里, 1表示b2表示c ,等等,因為我們按順序堆疊a, b, c, d

我只是先堆疊他的數組,然后使用 numpy 方法:

import numpy as np

a = np.array([[1,200],[4,5]])
b = np.array([[11,33],[65,666]])
c = np.array([[1,2040],[54,522]])
d = np.array([[1,3],[685,222]])

s = np.stack((a,b,c,d))

現在您可以輕松找到最大值的索引(因此 0 => a、1 => b 等):

max_value = s.max(axis=0)
argmax_value = s.argmax(axis=0)

您甚至可以將它們堆疊在一起:

result = np.dstack((max_value, argmax_value)).reshape(-1, 2)

# array([[  11,    1],
#        [2040,    2],
#        [ 685,    3],
#        [ 666,    1]], dtype=int64)

如果您確實需要列表中的字母,現在可以將第二列映射到您的字母:

# should not be too many arrays... ;-)
mapper = {i: chr(ord('a') + i) for i in range(s.shape[0])}
result_list = [(x, mapper[y]) for x, y in result]

但是一般來說,如果你的邏輯需要知道一個變量的名字,那么設計就是錯誤的。 您可能應該使用序列容器(列表、數組等),例如第一個代碼框中的堆疊數組。

只需將它們一個一個地堆疊起來:

[i for i in range(100) if i > 10 if i < 50]

生成 11 到 49(含)之間的整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM