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

时间:2022-03-16 21:17:12

So i have a list and a for loop (still a beginner sorry) and i want this code but in a more simplified way and without a new backwards list. ^The edit

所以我有一个列表和一个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: Would like as few lines as possible (im able to do it in 8 lines but would like at least 3-4) :/

PS:想尽可能少的线(我能够在8行但是至少需要3-4行):/

2 个解决方案

#1


1  

First, don't use list for your variables: it's a built-in function.

首先,不要为变量使用list:它是一个内置函数。

Second, print slices:

二,打印切片:

for i in range(len(l)):
    print(list(reversed(l[:i+1])))

#2


1  

You may use range here:

你可以在这里使用范围:

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

OR, in one line as:

或者,在一行中:

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

Both of these will print:

这两个都将打印:

A
B A
C B A

I am not sure whether this is what is desired. This result is based on:

我不确定这是否是所期望的。此结果基于:

How can i make it so A will be printed and then B and A, and finally C and B and A.

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

#1


1  

First, don't use list for your variables: it's a built-in function.

首先,不要为变量使用list:它是一个内置函数。

Second, print slices:

二,打印切片:

for i in range(len(l)):
    print(list(reversed(l[:i+1])))

#2


1  

You may use range here:

你可以在这里使用范围:

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

OR, in one line as:

或者,在一行中:

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

Both of these will print:

这两个都将打印:

A
B A
C B A

I am not sure whether this is what is desired. This result is based on:

我不确定这是否是所期望的。此结果基于:

How can i make it so A will be printed and then B and A, and finally C and B and A.

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