如何从lis中选择单个表达式

2024-04-26 21:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

以前在我的GCSE NEA计算评估中,我向一些2-D lis寻求帮助,在几个成员(包括一个叫dshort的成员)的帮助下,我能够实现我所需要的第一步。现在我需要选择一个表达式,以便它输出一个问题,并允许用户输入答案,而不是单独显示整个问题列表。你知道吗

def easy():
  stageone = [["carry on waywardson" , "Kansas"],
              ["Back In Black", "Ac/DC"],
              ["smoke on the water", "Deep purple"],
              ["sweet home albama", "Lynard Skynyrd"],
              ["another brick in the wall","Pink Floyd"]]
  for entry in stageone:
      shortTitle = ' '.join([word[0] for word in entry[0].split(' ')])
      print(shortTitle, entry[1])

我需要一首歌曲和作家被输出,这样我就可以编码,允许用户输入他们的答案。你知道吗

目前,当我运行我的代码,它会把所有的歌曲首字母和艺术家的名字,而不是这样做,以便用户可以回答它。你知道吗

(再次感谢dshort为我提供了这段代码。)


Tags: the答案代码用户inforon成员
1条回答
网友
1楼 · 发布于 2024-04-26 21:02:02

您可以使用yield语句根据需要生成项目:

A generator is a type of collection that produces items on-the-fly and can only be iterated once. By using generators you can improve your application's performance and consume less memory as compared to normal collections, so it provides a nice boost in performance.

here

因此,在代码中,只需将print更改为yield,然后使用next()方法从生成器中获取项。你知道吗

def easy():
  stageone = [["carry on waywardson" , "Kansas"],
              ["Back In Black", "Ac/DC"],
              ["smoke on the water", "Deep purple"],
              ["sweet home albama", "Lynard Skynyrd"],
              ["another brick in the wall","Pink Floyd"]]
  for entry in stageone:
      shortTitle = ' '.join([word[0] for word in entry[0].split(' ')])
      yield (shortTitle, entry[1])
yieldPoint = easy()
#Question
print(next(yieldPoint)) #('c o w', 'Kansas')
#Question
print(next(yieldPoint)) #('B I B', 'Ac/DC')

相关问题 更多 >