Reputation: 31
I'm trying to find a way to store in a variable of all the numbers from the players within allPlayers
I have been recommended to use the for loop which works but when you go to use it globally it only shows the last number not all of them. Preferably I would like it to be all within one line putting it into a variable but whatever is the simplest.
player1 = ['David.G', '1204', '4th Catogory']
player2 = ['John.D', '1000', 'Unranked']
player3 = ['Barry.M', '1932', '1st Catogory']
player4 = ['Steven.H', '1844', '1st Catogory']
allPlayers = [player1, player2, player3, player4]
for player in allPlayers:
fideRankings = player[1]
global fideRankings
print("")
print(fideRankings)
Result is: 1204 1000 1932 1844
1844
I was looking for it to print the same four numbers outside the for loop.
Upvotes: 3
Views: 52
Reputation: 327
player1 = ['David.G','1204','4th Catogory']
player2 = ['John.D','1000','Unranked']
player3 = ['Barry.M','1932','1st Catogory']
player4 = ['Steven.H','1844','1st Catogory']
allPlayers = [player1,player2,player3,player4]
for i in allPlayers:
print(i[1],end=" ")
if you just want to print it outside of for loop:
player1 = ['David.G','1204','4th Catogory']
player2 = ['John.D','1000','Unranked']
player3 = ['Barry.M','1932','1st Catogory']
player4 = ['Steven.H','1844','1st Catogory']
allPlayers = [player1,player2,player3,player4]
string = ""
for i in allPlayers:
string = string + " " + str(i[1])
print(string)
you can always use string.split(" ")
to get those numbers in list if you need to use those numbers in future.
Upvotes: 1
Reputation: 762
Using list comprehension
player1 = ['David.G','1204','4th Catogory']
player2 = ['John.D','1000','Unranked']
player3 = ['Barry.M','1932','1st Catogory']
player4 = ['Steven.H','1844','1st Catogory']
allPlayers = [player1,player2,player3,player4]
print(" ".join([player[1] for player in allPlayers]))
result will be
1204 1000 1932 1844
or use as below if you need each player details in new lines
print("\n".join([player[1] for player in allPlayers]))
Result will be as below
1204
1000
1932
1844
Upvotes: 0
Reputation: 1972
You can use an empty list to append the numbers then print it out all together. Like this:
player1 = ['David.G','1204','4th Catogory']
player2 = ['John.D','1000','Unranked']
player3 = ['Barry.M','1932','1st Catogory']
player4 = ['Steven.H','1844','1st Catogory']
allPlayers = [player1,player2,player3,player4]
empty_list = []
for player in allPlayers:
fideRankings = player[1]
empty_list.append(fideRankings)
print(empty_list)
Hope it helps :)
Upvotes: 0
Reputation: 5660
Try:
>>> print([i[1] for i in allPlayers])
['1204', '1000', '1932', '1844']
This uses a list comprehension. It is equivalent to:
>>> ns = []
>>> for i in allPlayers:
... ns.append(i[1])
>>> ns
['1204', '1000', '1932', '1844']
Upvotes: 0