gpt4 book ai didi

python - 如何从列表中选择单个表达式

转载 作者:太空宇宙 更新时间:2023-11-03 20:29:15 25 4
gpt4 key购买 nike

之前,在我的 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 为我提供了这段代码。)

最佳答案

您可以使用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')

关于python - 如何从列表中选择单个表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com