【问题标题】:Printing a value from a list in python if the condition is true如果条件为真,则从 python 中的列表中打印一个值
【发布时间】:2020-08-10 04:18:12
【问题描述】:

我试图在 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')

谢谢

【问题讨论】:

    标签: python python-3.x list pycharm


    【解决方案1】:

    而不是

    if i is type(str):
    

    我想你想要:

    if type(i) is str:
    

    但更好的是,使用:

    if isinstance(i, str):
    

    【讨论】:

    • 感谢您,这解决了 if 语句的前半部分从列表中拉出字符串,但是,我的结果仍然打印 5 行,如 'There are no strings in the list item is string列表中没有字符串 列表中没有字符串 列表中没有字符串 '我将如何使它读取列表并仅返回字符串值,这可能吗?
    • 您的else: 部分指的是在for 循环的每次迭代中执行的if,因此它会为列表中不是字符串的每个项目打印消息。去掉else:和下一行,就不会打印消息了……
    • 谢谢你,你不仅给了我答案,还为我解释了背后的理由。谢谢
    【解决方案2】:

    如果您只想打印字符串,请尝试以下代码。如果 if 条件失败,则执行 else 条件。

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

    或

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

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      相关资源
      最近更新 更多