Python-需要帮助来简化我的代码

时间:2016-12-03 18:36:00

标签: python list for-loop list-comprehension

所以我有一个列表和一个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行):/

1 个答案:

答案 0 :(得分:1)

您可以在此处使用range

my_str = ['A', 'B', 'C']
for i, val in enumerate(my_str):
    print ' '.join(my_str[i::-1])

或者,在一行中:

print '\n'.join(' '.join(my_str[i::-1]) for i in range(len(my_str))

这两个都会打印出来:

A
B A
C B A

我不确定这是否符合要求。该结果基于:

  

我怎样才能这样做,所以A将被打印,然后是B和A,最后是C和B和A.