Issue
You have a list of list and trying to convert it to a dictionary that maps names of athletes to lists of their jump length, the jumps also need to be converted to int.
I found a solution, but it uses the function maps and to be honest I don't get how maps work well enough. Whats another way to solve this problem (the more basic the better)
jumps = [
['Student', 'Jump 1', 'Jump 2', 'Jump 3'],
['James', '10', '9', '8'],
['Finn', '18', '19', '21'],
['Blu', '14', '15', '17'],
['John', '15', '16', '16'],
['Kim', '13', '19', '13'],
['Lacey', '19', '17', '10']]
def jump_distance(jumps):
dict = {}
for d in jumps[1:]:
dict[d[0]] = list(map(int, d[1:]))
return dict
Feel free to explain how this works as well:
dict[d[0]] = list(map(int, d[1:]))
Solution
Sometimes comprehensions can make the code both more succinct and easier to read.
In this case, if we know that jumps
will have the structure in the example, with the first element containing the headings and the remaining elements containing the data, then we could solve the problem using an outer dictionary comprehension and an inner list comprehension as follows.
def jump_distances(jumps):
return {jump[0]: [int(d) for d in jump[1:]] for jump in jumps[1:]}
With the list in your example, this returns:
{
'James': [10, 9, 8],
'Finn': [18, 19, 21],
'Blu': [14, 15, 17],
'John': [15, 16, 16],
'Kim': [13, 19, 13],
'Lacey': [19, 17, 10]
}
To answer your other question, list(map(int, d[1:]))
maps each element in the sub-list d[1:]
to whatever the function int
returns with that element as an argument. For example:
def stars(n):
return "*" * n
for x in map(stars, [1, 2, 3]):
print(x)
outputs
*
**
***
map
actually doesn't return a list, but it is easy enough to convert what it returns to a list using list
. The following two expressions produce the same list, but I think the second is more readable.
list(map(stars, [1, 2, 3]))
[stars(i) for i in [1, 2, 3]]
(Both expressions produce the list ['*', '**', '***']
.)
Answered By - Richard Ambler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.