User0123456789
User0123456789

Reputation: 758

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 appropriate list. This is my code so far:

myList = [['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: ")

if prompt in myList:
    print(myList["""What do I put in here???"""])

So if I entered "E1234" as prompt, I want this code to look through myList, pick up the list and display it. Please help me, I'm stuck.

Update

Sorry that I haven't mentioned it before, but the boundaries are to use lists, not dictionaries.

Upvotes: 2

Views: 81

Answers (3)

Alexandru Godri
Alexandru Godri

Reputation: 538

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])

Upvotes: -1

kingledion
kingledion

Reputation: 2500

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)])

Upvotes: 4

Mureinik
Mureinik

Reputation: 311188

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

Upvotes: 2

Related Questions