【问题标题】:How to make python go through specific part of for loop go first?如何让python首先通过for循环的特定部分?
【发布时间】:2018-02-20 19:07:54
【问题描述】:

假设我们有一个列表(它在这个列表中有更多列表,但我仅出于演示目的而包含一个):

list = [
    ['X', ['House A', 'Location 4', 'Right'],
          ['House D', 'Location 3', 'Left'],
          ['House C', 'Location 2', 'Right']]

我做了一个这样的函数:

def example(lists):
    for element in lists:
       if element[0] == 'House A':
            if element[1] == 'Location 4':
                if element[2]  == 'Right':
                    direction = 0
                    house1(loc4, direction)
                elif element[2] == 'Left':
                    direction = 180
                    house1(loc4, direction)
    if element[0] == 'X':
             graffiti()

我怎样才能做到这一点,如果在for循环之后一切都是真的(在这个例子中我可能没有正确完成for循环,但在我的代码的正确版本中它是正确的),它会绘制涂鸦( )。 (做海龟图形)

【问题讨论】:

  • 在编写代码块时,请使用 4 个空格缩进而不是反引号,反引号仅用于 inline 代码
  • 还有“代码格式”按钮和实时预览...
  • “但在我的代码的正确版本中它是正确的”。那你为什么不给我们看看正确的版本呢?
  • “for 循环之后一切都是真的”到底是什么意思?什么是“一切”?
  • @Jarek.D 没有为作业显示正确的版本,如果出现这种情况,也不想得到任何抄袭。

标签: python for-loop boolean conditional turtle-graphics


【解决方案1】:

我没有测试这段代码:

direction_map = {'Right': 0, 'Left': 180}
def example(lists):
    for element in lists:
        if element[0] == 'House A' and element[1] == 'Location 4':
            house1(loc4, direction_map[element[2]])
    if list(element for element in lists if (element[0] == 'House A' 
            and element[1] == 'Location 4')) and (element[2] in direction_map)):
        ....
    if element[0] == 'X':
         graffiti()

但根据我从您发布的内容中了解到的情况,any 方法可能就是您正在寻找的。​​p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 2021-06-02
    • 2014-08-30
    • 2020-09-22
    相关资源
    最近更新 更多