[英]Filter nested list based on value of sub-list
所以這個問題很難解釋。 說我有一個成績清單清單和一個名字清單,例如:
a=[[90,50,40],'Josh']
b=[[85,60,90],'Becky']
c=[a,b]
所以c將是:
c=[[[90,50,40],'Josh'],[[85,60,90],'Becky']]
現在讓我們說這份名單要長得多,我對一個獲得[100,100,100]成績清單的學生感興趣。 我該如何循環?
從我對MATLAB的使用中,我知道我使用c [:] [0]來獲得成績的“清單”。
現在,我想做一些事情:
target=[100,100,100]
if target in c[:][0]:
print 'we got a smart fella in the hood'
如何在python中做到這一點? 非常感謝!
您應該像這樣迭代:
c = [[[90,50,40],'Josh'],[[85,60,90],'Becky'], [[100,100,100],'Mano']]
target = [100,100,100]
for grade, name in c:
if grade == target:
print name
它將打印:
Mano
如果要使所有名稱的列表都滿足上述條件,則可以將列表理解表達式用作:
names = [name for grade, name in c if grade == target]
根據您的代碼,矩陣c將顯示為嵌套列表結構。 挖掘水平...
c[1] is [[85,60,90],'Becky']
c[1][0] is [85,60,90]
c[1][0][2] is 60
那應該為您解釋命名。 現在,您需要檢查分數列表c [*] [0]以獲取目標值。 如果需要完全匹配,這很容易:構建一個臨時值列表並報告是否存在匹配項。
if target in [record[0] for record in c]:
print "Smart person exists"
如果需要打印名稱列表,請嘗試
print [record[1] for record in c if record[0] == target]
那會讓你動起來嗎?
我建議使用基於類的方法來擺脫嵌套列表
class Student():
def __init__(self, name, scores):
self.name = name
self.scores = scores
def has_perfect_scores():
return all(score == 100 for score in self.scores)
然后,
c = [ Student('Josh', [90,50,40]), Student('Becky', [85,60,90]) ]
for student in c:
if student.has_perfect_scores():
print 'we got a smart fella in the hood named {}'.format(student.name)
對於任何學生,您都可以瀏覽他們的scores
列表
如果您只需要知道是否有匹配項,則可以執行以下操作:
c=[[[90,50,40],'Josh'],[[85,60,90],'Becky']]
target = [85,60,90]
if target in [i[0] for i in c]:
print "true"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.