Trouble Printing A List Within A List
I want to print a list within a list, but not this way: print(myList[1]) I want to be able to search through the list, find the correct list based on a user input and print the ap
Solution 1:
The implementation you are thinking of is a dict().
https://docs.python.org/3.5/library/stdtypes.html#mapping-types-dict
A dict provides you with the ability to access data by a key, in this case the player name.
mydict = {'E1234': ['12/09/14','440','A','0'],'E3431': ['10/01/12','320','N','120'],'E0987': ['04/12/16','342','A','137']}
prompt = input("Enter a player name: ")
print(mydict.get(prompt, "Player not found"))
EDIT:
Also you can turn a list into a dict using:
mydict = {key: value for (key, value) in [(x[0], [x[1], x[2], x[3], x[4]]) for x in myList]}
EDIT2:
Ok fine, if you are not allowed to use dictionaries at all, then simulate one:
fake_dict_keys = [x[0] for x in myList]
print(myList[fake_dict_keys.index(prompt)])
Solution 2:
Edit @kingledion answered, the correct implementation would probably be to use a dictionary. If you insist on this list of lists data structure, you could use a list comprehension to filter out only the relevant lists:
details = [x for x in myList if x[0] == prompt]
if details:
print details
Solution 3:
You can convert your list to a dictionary and then do the task. Example below:
myList = [['E1234','12/09/14','440','A','0'],['E3431','10/01/12','320','N','120'],['E0987','04/12/16','342','A','137']]
myDict = { i[0]: i for i in myList }
prompt = input("Enter a player name: ")
if prompt in myDict:
print(myDict[prompt])
Post a Comment for "Trouble Printing A List Within A List"