This is a typical python coding challenge. Many beginners have a hard time handling it.
For example, we have a test array as:
test = [[1,2],[1,3],[2,4],[2,1],[2],[5,1],[3,4]]
Q1: count the number of pairs in the list.
Q2: count the number of pairs for 1.
I know I can use the least/greatest function in SQL to do the job, but I don't know how to do it in python, especially in 2 dimension arrays.
Expected result for Q1 is 5 ([1,2],[1,3],[2,4],[5,1],[3,4])
Expected result for Q2 is 3 (2,3,5)
CodePudding user response:
How about the following:
test = [[1,2],[1,3],[2,4],[2,1],[2],[5,1],[3,4]]
unordered_pairs = set(frozenset(l) for l in test if len(l) == 2)
print(unordered_pairs)
# {frozenset({3, 4}), frozenset({1, 2}), frozenset({2, 4}), frozenset({1, 5}), frozenset({1, 3})}
q1 = len(unordered_pairs)
q2 = sum(1 in p for p in unordered_pairs)
print(q1, q2) # 5 3
CodePudding user response:
len([k in test if len(k)==2])
and len([k for k in test if 1 in k])
should get you there.