对Python来说很新,所以如果标题不够混淆,我会感激一些帮助。我将通过一个我想要实现的目标来最好地解释这一点。
Number = [25, 30, 36]
Ratings = [ [101, 201, 301], [102, 202, 302], [103, 203, 304,] ]
what_i_want = [ [ [101, 25],[201,30],[301,36] ], [ [102,25],[202,25],[302,36] ], [ [103,25],[203,30],[303,36] ] ]
我完全不知道如何做到这一点,我尝试使用嵌套for循环,但列表最终看起来像这样:
list = [ ([101, 201, 301], 25), ([102, 202, 302], 30), ([103, 203, 304,], 36) ]
另外,我将处理一个非常大的列表,所以提高效率和速度的方法也会非常有用。
答案 0 :(得分:4)
您可以将zip
与列表理解结合使用:
Number = [25, 30, 36]
Ratings = [ [101, 201, 301], [102, 202, 302], [103, 203, 304,] ]
new_data = [[[a, b] for a, b in zip(i, Number)] for i in Ratings]
输出:
[[[101, 25], [201, 30], [301, 36]], [[102, 25], [202, 30], [302, 36]], [[103, 25], [203, 30], [304, 36]]]
答案 1 :(得分:0)
您可以使用嵌套for循环。
Number = [25, 30, 36]
Ratings = [ [101, 201, 301], [102, 202, 302], [103, 203, 304,] ]
list = []
for i in xrange(len(Ratings)): #Iterate through outer list.
list.append([]) #Add new middle list to list.
for j in xrange(len(Ratings[i])): #Iterate through inner list.
list[i].append([Ratings[i][j],Number[j]])
输出:
list = [[[101, 25], [201, 30], [301, 36]], [[102, 25], [202, 30], [302, 36]], [[103, 25], [203, 30], [304, 36]]]
答案 2 :(得分:0)
您可以在一行中完成而无需导入任何模块或使其更复杂:
只需使用lambda:
$ git push origin branch-name --force
输出:
void printNumbers(int a)
{
if(a > 0) {
printf("%d\n", a);
printNumbers(a-1);
}
}
int main()
{
printNumbers(10);
}