Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果条件为true,则在python中打印列表中的值_Python_Python 3.x_List_Pycharm - Fatal编程技术网

如果条件为true,则在python中打印列表中的值

如果条件为true,则在python中打印列表中的值,python,python-3.x,list,pycharm,Python,Python 3.x,List,Pycharm,我尝试在Python中执行一个相对基本的操作,我尝试从列表中打印一个值,如果它是一个特定类型的值,那么举个例子,如果它是一个字符串类型,则打印该值 这是我到目前为止,我相信我的结构是有点不正确,也作为例外,也是打印5次 x = [ 1, 'string', 3, 4, 5 ] for i in x: if i is type(str): print('item is {}'.format(i)) else: print('There are n

我尝试在Python中执行一个相对基本的操作,我尝试从列表中打印一个值,如果它是一个特定类型的值,那么举个例子,如果它是一个字符串类型,则打印该值

这是我到目前为止,我相信我的结构是有点不正确,也作为例外,也是打印5次

x = [ 1, 'string', 3, 4, 5 ]
for i in x:
     if i is type(str):
        print('item is {}'.format(i))
     else:
        print('There are no strings in the list')
谢谢

而不是

if i is type(str):
我想你想要:

if type(i) is str:
但更好的是,使用:

if isinstance(i, str):
而不是

if i is type(str):
我想你想要:

if type(i) is str:
但更好的是,使用:

if isinstance(i, str):

如果只想打印字符串,请尝试下面的代码。如果条件失败,将执行else条件

x = [ 1, 'string', 3, 4, 5 ]
for i in x:
     if type(i) is str:
        print('item is {}'.format(i))


如果只想打印字符串,请尝试下面的代码。如果条件失败,将执行else条件

x = [ 1, 'string', 3, 4, 5 ]
for i in x:
     if type(i) is str:
        print('item is {}'.format(i))


感谢这一点,它解决了if语句的前半部分从列表中提取字符串,我的结果仍然是打印5行,如“列表中没有字符串项目是字符串列表中没有字符串列表中没有字符串列表中没有字符串”如何使其读取列表并仅返回字符串值,这可能吗?您的
else:
部分是指在
for
循环的每次迭代中执行的
if
,因此它为列表中不是字符串的每个项目打印消息。删除
否则:
下一行将不会打印消息…谢谢你,你不仅给了我答案,还为我解释了背后的理由。感谢Hanks解决了if语句的前半部分从列表中提取字符串,我的结果仍然是打印5行,如“列表中没有字符串项目是字符串列表中没有字符串列表中没有字符串列表中没有字符串”如何使其读取列表并仅返回字符串值,这可能吗?您的
else:
部分是指在
for
循环的每次迭代中执行的
if
,因此它为列表中不是字符串的每个项目打印消息。删除
否则:
下一行将不会打印消息…谢谢你,你不仅给了我答案,还为我解释了背后的理由。谢谢