【问题标题】:Accessing values of tuples inside lists in if statements在 if 语句中访问列表中元组的值
【发布时间】:2021-08-11 04:53:10
【问题描述】:

这里是python初学者。 According to this thread,,我学会了如何访问列表中元组的值。

这是上面帖子中的答案:

[x[1] for x in L]

我这里有一个元组列表:

[('w', False), ('o', True), ('r', False), ('d', False)]

我想读取每个元组中的 True/False 值,如果值为 false,则打印下划线,如果值为 true,则打印字符。例如,在上面的列表中,由于 'o' 是 True 的项目,我想打印 _o__

这是我迄今为止一直在尝试的,我觉得我的方向是正确的,但是由于我正在写这个线程,它显然不起作用:

for char in word: #part i need help on
  if [x[1] for x in word] == True:
    print("_", end="")
  elif [x[1] for x in word] == False:
    print(word[char], end="")

如果需要更多信息,这是完整的代码(刽子手游戏的开始,还有很长的路要走),但特别是我需要上述代码块的帮助:

randomword = "word" #will add random words when it works properly
word = [(char, False) for char in randomword] #splits randomword into list of tuples of different characters with a false value assigned because no letters have been guessed yet

def getLetter(): #letter guessing function, limits input to one character
    guess = input("Guess a letter: ")
    if len(guess) != 1 or (guess.isalpha()) == False:
        while len(guess) != 1 or (guess.isalpha()) == False: 
            print("Must be" + "\033[96m one letter!" + "\033[0m Try again.")
            guess = input("Guess a letter: ")
    return guess

guess = getLetter()

for char in range(word.__len__()):
  if word[char][0] == guess.lower():
    word[char] = (guess, True) #a correct guess changes the False to True
print(word) 

for char in word: #part i need help on
  if [x[1] for x in word] == True:
    print("_", end="")
  elif [x[1] for x in word] == False:
    print(word[char])

【问题讨论】:

    标签: python list for-loop tuples list-comprehension


    【解决方案1】:

    我会说你有点过于复杂了。而是尝试这样的事情。

    lst = [('w', False), ('o', True), ('r', False), ('d', False)]
    for tup in lst:
      if tup[1] == True:
          print(tup[0],end="")
      elif tup[1] == False:
        print('_', end="")
    

    【讨论】:

    • 您只需要elseif tup[1]: / print(tup[0],end='') / else: / print('_',end='')
    • 这样简单易懂,谢谢!
    • @TimRoberts,是的,我知道。但我想把它留在那里,因为 OP 有它。也许 lst 的元组可能包含布尔值以外的其他内容。
    【解决方案2】:

    使用列表推导可以这样做:

    word = [('w', False), ('o', True), ('r', False), ('d', False)]
    new_word = [elements[0] if elements[1]==True else "_" for elements in word]
    for element in new_word:
        print(element,end="")
    

    这里逐个提取列表的元素,因为它是一个有两个元素的元组,所以它们的第一个索引被检查为真或假,并根据值分配字符或_,这是使用完成的python中的三元运算符。

    【讨论】:

    • 你可以使用这样的东西来使它成为一个单行''.join([elements[0] if elements[1]==True else "_" for elements in word])for 末尾的循环效率低下:)
    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    相关资源
    最近更新 更多