对列表中的每个项目的if语句 [英] if statement against each item in a list

查看:62
本文介绍了对列表中的每个项目的if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中执行以下操作,但是我收到了无效的语法错误:

I am trying to do something like the following in python, but i am getting an invalid syntax error:

network_n = 192.168.38
octate_n = network_n.split(".")
if (len(o) [for o in octate_n]) == 3:

但是当我运行它时,我得到了:

But when i am run it, i get:

if (len(o) [for o in octate_n]) == 3:
                  ^
SyntaxError: invalid syntax

我的问题是使用if语句,那里出了什么问题?

My problem is with the if statement, what is wrong there ?

我承认我对if语句中的() [] 之间的区别有一个粗略的认识,所以我很高兴您能给我简短的解释.

I admit that i have a rough idea about the difference between the () and the [] in the if statement, so i would be glad that you give me a short explanation about it.

推荐答案

使用 全部 :

if(all(len(o) == 3 for o in octate_n)):
    # do stuff

关于您的秒数问题, [octate_n中的o表示o] 创建一个列表,该列表由 octate_n 中的所有项目组成(这称为生成器,它将产生 octate_n 的所有项目(这称为生成器表达式).

About your seconds question, [o for o in octate_n] creates a list that consists of all items in octate_n (this is called a list comprehension), while (o for o in octate_n) creates a generator that will yield all the items of octate_n (this is called a generator expression).

这篇关于对列表中的每个项目的if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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