【发布时间】:2016-12-03 18:36:00
【问题描述】:
所以我有一个列表和一个 for 循环(对不起,仍然是初学者),我想要这段代码,但以更简化的方式,没有新的向后列表。 ^编辑
lyrics = [["First", "and a partride in a pear tree",], ["second", "2 things"], ["Third", "3 things"], ["Fourth", "4 things"], ["Fifth", "5 things"], ["Sixth", "six things"], ["Seven", "7 things"], ["Eigth", "8 things"], ["Nineth", "nine things"], ["tenth", "Ten things"], ["eleventh", "eleven things"], ["Twelveth", "twelve things"]]
backwards = []
for i in range(12):
print("On the", lyrics[i][0], "my true love gave to me, lyrics[i][1])
backwards.append(lyrics[i][1])
for each in backwards:
print (each) #Forgot how i did it in the reverse order but i want this in a more simplified version to learn from.
PS:希望尽可能少的行(我能够在 8 行中完成,但希望至少 3-4 行):/
【问题讨论】:
-
您能告诉我们您是如何在 8 行中实现这一目标的吗?
-
在学校设法做到了,但我将每个索引存储在另一个列表中,然后逐行打印列表:/
-
您甚至可以在一行中实现它。向我们展示您尝试了什么以及您想要的输出。我们将提供实现它的最佳方法。这就是魔术在 SO 上的工作方式:)
-
好吧,我重做我的 8 行版本。
-
@MoinuddinQuadri,你如何在一行中做到这一点? (只是好奇;除非你的意思是你可以把
for循环头和打印在同一行)。
标签: python list for-loop list-comprehension