【问题标题】:Can I use a for-loop to add something to a variable's value multiple times in python? [duplicate]我可以使用for循环在python中多次向变量的值添加一些东西吗? [复制]
【发布时间】:2019-10-11 10:18:44
【问题描述】:

我正在尝试使用 for 循环计算字符串“red”在此列表中出现的次数。但是,按照它的编写方式,每次尝试打印 how_much_red 的计数时,我的总数仍然为零。

另外,由于某种原因,无论我做什么,它也说'''name 'how_much_Green' 没有定义''',即使我将它命名在与我做红色相同的地方。

基本上,我不明白为什么它不起作用。我是 Python 新手,我想我只是误解了 for 循环的位置。

我正在尝试制作一个程序,在其中生成一个随机列表,分析以检查它是否满足某个条件(美化的 True/False 语句),然后在该列表中搜索字符串或对象的存在,并添加到全球柜台。我希望能够为 1000 个随机列表执行此操作并记录每次出现在其中的内容,因此计数必须是全局的和累积的

我试图将我的颜色计数变量放在函数之外,但后来 python 给了我错误消息,说“在赋值之前引用了局部变量。”

BadHand = False
Hand = True
Hand_to_analyze = []
my_hand = ['red', 'blue', 'green']
def HandAnalyzer(hand, cards):
    if hand:
        Hand_to_analyze.append(cards)
        print("hand is True")

        how_much_Green = 0
        how_much_Red = 0
        for _ in my_hand:
            if 'green' == _:
                how_much_Green +=1   #this is where I usually get my error 
            if 'red' == _:
                how_much_Red +=1   #apparently this is fine???

            elif 'red' != _:
                pass
            elif 'green' != _:
                pass

    elif hand:
        pass
    else:
        pass

def repeater():
    #this is just used as a way for the program to do this multiple times
    for ThisManyTimes in range(4):
        HandAnalyzer(Hand, my_hand)


repeater()
print(Hand_to_analyze)
print(how_much_Red)
print(how_much_Green)

我希望最后 2 个打印语句的读数为: 4 4

但它们实际上是: 0 名称错误:未定义“how_much_Green”

【问题讨论】:

  • 如果您打算在循环中使用_ 作为变量,请不要使用for _for _ 是说您不关心迭代变量的传统方式。给它一个真实的名字。
  • 你不需要 elifelse 块。
  • 如果只输入pass,则不必使用elif/else
  • HandAnalyzer 使用return how_much_Green, how_much_Red 然后你可以使用how_much_Green, how_much_Red = HandAnalyzer()

标签: python list for-loop counter


【解决方案1】:

你可以使用全局变量

BadHand = False
Hand = True
Hand_to_analyze = []
my_hand = ['red', 'blue', 'green']
how_much_Green = 0
how_much_Red = 0

def HandAnalyzer(hand, cards):
    global how_much_Green
    global how_much_Red
    if hand:
        Hand_to_analyze.append(cards)
        print("hand is True")

        for _ in my_hand:
            if 'green' == _:
                how_much_Green +=1   #this is where I usually get my error 
            if 'red' == _:
                how_much_Red +=1   #apparently this is fine???

            elif 'red' != _:
                pass
            elif 'green' != _:
                pass

    elif hand:
        pass
    else:
        pass

def repeater():
    #this is just used as a way for the program to do this multiple times
    for ThisManyTimes in range(4):
        HandAnalyzer(Hand, my_hand)


repeater()
print(Hand_to_analyze)
print(how_much_Red)
print(how_much_Green)

【讨论】:

  • 嘿,非常感谢。你知道为什么 how_much_Red 没有给我错误,但 how_much_Green 是吗?
  • 他们都会给出错误,How_much_Green 只是第一个,所以它停在那里,除非在函数之外定义了一个并且你错过了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
相关资源
最近更新 更多