[英]Get the count of first field in the list of lists by iterating through for loop
通過遍歷列表的列表,我試圖從列表中的所有列表中獲取第一個字段的計數,並實現一些if-else邏輯。 不知道是否可以在Iterator中進行。
Input:-
[ [1,'A'],[1,'B'],[2,'C'],[-1,'D'],[-1,'D'] ]
Output:-
Invalid row
Invalid row
Valid row
Invalid row
Invalid row
Comments :-
如果任何值的計數均大於1,則所有此類行均無效,否則這些行均有效。
from collections import Counter
counts = Counter()
for l in myList:
counts[l[0]] += 1
for l in myList:
if counts[l[0]] > 1:
print("Invalid row")
else:
print("Valid row")
您必須將第一個元素的計數存儲在計數器中,然后執行另一個for循環以遍歷列表:
首先,商店數量:
from collections import Counter
l = [ [1,'A'],[1,'B'],[2,'C'],[-1,'D'],[-1,'D'] ]
c= Counter()
for element in l:
c[element[0]] += 1
print c
Out: Counter({1: 2, -1: 2, 2: 1})
現在,遍歷列表列表以檢查哪些有效,哪些無效:
for element in l:
if c[element[0]] > 1:
print "Invalid"
else:
print "Valid"
從評論中跟進:如果要將計數附加到列表中的每個元素:
for element in l:
element.append(c[element[0]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.