Home > OS >  How to swap the positions of two-dimensional lists?
How to swap the positions of two-dimensional lists?

Time:10-02

I want to change position [85', pass'] to be ['pass', 85].

And here is my code:

gradebook= [
  ["physics",  98],  
  ["calculus", 97],  
  ["poetry",   85],  
  ["history",  88]  
]
print(gradebook)

gradebook.append(["computer science", 100])
print(gradebook)
gradebook.append(["visual art", 93])
print(gradebook)

# Mengubah nilai 2D list
gradebook[-1][-1]= 98 # menambahkan 5 nilai dari 93 menjadi 98
print(gradebook)

gradebook[2].remove("poetry")# Menghapus poetry dan menggantikannya dengan pass
print(gradebook)
gradebook[2].append("pass")
print(gradebook)

CodePudding user response:

You can use this cool method to reverse the order of all items inside a list, in the case of [85,’pass’]:

item = gradebook[2]
gradebook[2] = item[::-1]
# gradebook[2] is now = [‘pass’,85]

What this basically does when you put in [::-1] is reverse the order of all items in the list.

When you put [] after a list, you can put in more than just the wanted index position for an item, you can call for items in a certain range and a step-size. Step size is like an interval for the list items, for example:

lis = [1,2,3,4,5,6]
print(lis[0:5:2])
# outputs 1, 3, 5

Skipped over every other number (step-size 2) in the range of index positions 0 to 5. So what python does when it reads [::-1] is first: the “::” is default for every item in the list, and second: -1 is our step-size, in this case python would return every item in the list in reversed order.

Hope this helps.

CodePudding user response:

We can use a list comprehension here:

gradebook= [
  ["physics",  98],  
  ["calculus", 97],  
  ["poetry",   85],  
  ["history",  88]  
]
output = [[x[1], x[0]] for x in gradebook]
print(output)
# [[98, 'physics'], [97, 'calculus'], [85, 'poetry'], [88, 'history']]

CodePudding user response:

>>> [[score, name] for [name, score] in gradebook]
[[98, 'physics'], [97, 'calculus'], [85, 'poetry'], [88, 'history']]

CodePudding user response:

gradebook[2]=[gradebook[2][1],gradebook[2][0]
print(gradebook)

Output

  • Related