Python:从列表中提取包含两个以上元素的元组

时间:2017-02-16 22:30:44

标签: python list tuples

鉴于这个元组列表:

l1=[(0, 90),
    (1, 532, 17),
    (2, 5080),
    (3, 2516, 94)]

如何提取所有具有两个以上元素的元组?在这种情况下,结果将是:

l2=[(1, 532, 17),(3, 2516, 94)]

2 个答案:

答案 0 :(得分:2)

使用列表理解并使用len进行过滤:

l2 = [tup for tup in l1 if len(tup) > 2]
print(l2)
# [(1, 532, 17), (3, 2516, 94)]

答案 1 :(得分:0)

使用列表推导过滤它:

CREATE VIEW match_result AS
SELECT m.match_id
     , concat_ws(' : ', t1.team, t2.team) AS home_vs_away_team
     , concat_ws(' : ', mt1.innings_score, mt2.innings_score) AS result
FROM   match           m
LEFT   JOIN match_team mt1 ON mt1.match_id = m.match_id AND mt1.home
LEFT   JOIN team       t1  ON t1.team_id = mt1.team_id
LEFT   JOIN match_team mt2 ON mt2.match_id = m.match_id AND NOT mt2.home
LEFT   JOIN team       t2  ON t2.team_id = mt2.team_id;

结果:

l1=[(0, 90),
    (1, 532, 17),
    (2, 5080),
    (3, 2516, 94)]

l2 = [x for x in l1 if len(x)>2]

print(l2)