在Python中嵌套if中的元素 [英] Counting elements in nested if in Python

查看:160
本文介绍了在Python中嵌套if中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个程序,可以打印超过3人观看的电影数量(存储在嵌套列表中的数据如下)。



list_movies = [('Spiderman 3',['John','jake','Ronald']),('Gravity',['james','jake','john','gerald']),

('终结者',['安妮','约翰尼','彼得','罗纳德','内维尔')]



我的尝试:



I want to create a program that can print the number of movies that was watched by more than 3 people(data stored in a nested list as below ).

list_movies = [('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald']),
('Terminator',['Anne','Johnny','Peter','Ronald','Neville'])]

What I have tried:

list_movies = [('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald']),
               ('Terminator',['Anne','Johnny','Peter','Ronald','Neville'])]



count2 = 0
for (movie,name) in list_movies:
    count = 0
    for (name) in list_movies:
        if name != '':
            count += 1
    if count > 3:
        count2 += 1
    
print(count)
print(count2)

推荐答案

你的内部循环应该遍历元组的第二项:

You inner loop should iterate over the second item of the tuple:
list_movies = [('Spiderman 3', ['John', 'jake','Ronald']),('Gravity',['james','jake','john','gerald']),
               ('Terminator',['Anne','Johnny','Peter','Ronald','Neville'])]



count2 = 0
for (movie,viewers) in list_movies:
    count = 0
    for (name) in viewers:
        if name != '':
            count += 1
    if count > 3:
        count2 += 1

print("last movie viewers: %d" % count)
print("count of movies having had more than three viewers: %d" % count2)


这篇关于在Python中嵌套if中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆