[英]Searching through a 2D array in python 2.7 if a char is in that position
您好,我試圖在我的數組中搜索某個字符是否在該位置,然后將其打印到控制台。
到目前為止,這是我的代碼。
students = [['Gary','Y'],['Steve','N'],['Tom','Y']]
for i in range (len(students)):
if students[i,1] == 'Y':
print (students(i,0))
您可以這樣做:
for student in students:
if student[1] == 'Y':
print(student[0])
如果您正在尋找一種班輪,那么:
print [student[0] for student in students if student[1]=='Y']
您沒有正確使用索引。 對於python,您需要按以下方式使用它:
for i in range (len(students)):
if students[i][1] == 'Y':
print (students[i][0])
除了其他答案,您還可以嘗試使用filter()
:
>>> students = [['Gary','Y'],['Steve','N'],['Tom','Y']]
>>> filtered = list(filter(lambda x: x[1] == 'Y', students))
>>> print(filtered)
[['Gary', 'Y'], ['Tom', 'Y']]
>>> print([x[0] for x in filtered])
['Gary', 'Tom']
您可以使用filter
,
filter(lambda i: i[1]=='Y', students)
可能:
students = [['Gary','Y'],['Steve','N'],['Tom','Y']]
for i in range (len(students)):
if students[i[2]] == 'Y':
print (students[i])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.