【问题标题】:How do I nest a For Loop w/ IF statement to return a new list?如何使用/ IF 语句嵌套 For 循环以返回新列表?
【发布时间】:2020-09-28 07:28:38
【问题描述】:

If 语句中的 return 可以附加一个列表吗?

python 是否知道列表元素实际上是字典,并且“子列表”会迭代这些元素?

我尝试在 For 之前指定数据类型,但这没有帮助

If 语句实际上是在访问字典吗?

我的代码:

In[1]: restaurants = [fork_fig, frontier_restaurant]
In [2]: def open_restaurants(restaurants):
    for sublsit in restaurants:
        op=[]
        if sublist.get('is_closed')==False:
            op.append(sublist.get('name'))

通过他们的代码:

In [1]: len(open_restaurants(restaurants))

Out[2]: NameErrorTraceback (most recent call last)
    <ipython-input-14-e78afc732a29> in <module>
    ----> 1 len(open_restaurants(restaurants)) # 1

    <ipython-input-13-56ad484d6dd9> in open_restaurants(restaurants)
          2     for sublsit in restaurants:
          3         op=[]
    ----> 4         if sublist.get('is_closed')==False:
          5             op.append(sublist.get('name'))
          6 

    NameError: name 'sublist' is not defined

接下来:我认为这是因为我定义的列表没有填充正确的信息。

In[3]: open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'

Out[4]:TypeErrorTraceback (most recent call last)
<ipython-input-15-bf5607d088f4> in <module>
----> 1 open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'

TypeError: 'NoneType' object is not subscriptable

【问题讨论】:

    标签: python-3.x for-loop if-statement typeerror nameerror


    【解决方案1】:
    1. 您的缩进可能不正确
    2. 您没有在函数中返回结果(可能是return op

    【讨论】:

    • if 语句中的 return 语句是什么样的? python是否知道列表元素实际上是字典并且子列表迭代这些元素?对不起,我很笨
    【解决方案2】:

    这里的问题是我输入了太多信息。

    最终完美运行的代码如下:

    def open_restaurants(restaurants):
        op=[]
        for sublist in restaurants:
            if sublist['is_closed']==False:
                op.append(sublist)
            return op
    
    1. 我将操作列表与 for 循环分开。
    2. 以前,NameError 表示子列表未定义,但它是 通过将其包含在For 中来定义;修复我删除了.get()和 将其替换为列表形式x[]
    3. 最后,从 .append() 函数中分离返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多