-2

Please, tell me what do string 'sorted(args, key=len)[0] ?

names = ['Bruce', 'Clark', 'Peter'] 
heroes = ['Batman', 'Superman', 'Spiderman']

def shortest_seq(*args):
     return range(len(sorted(args, key=len)[0]))

g = ((names[i], heroes[i]) for i in shortest_seq(names, heroes))
for item in g:
    print(item)
user2390182
  • 72,016
  • 6
  • 67
  • 89
Aleksei Grabor
  • 153
  • 2
  • 8

1 Answers1

1

The sorted function takes an optional argument, key, which is the function used to measure the size of the elements of your list. Thus, in your case, you're sorting a collection of lists by their length.

Example:

L1 = [1, 2, 3, 4]
L2 = sorted(L1, key=lambda x: -x)  # [4, 3, 2, 1]
L3 = sorted(L1, key=lambda x: x % 2)  # [2, 4, 1, 3]

Thus, the function

def shortest_seq(*args):
    return range(len(sorted(args, key=len)[0]))

Takes any number of iterables and returns a list (not really, a range object, but close enough) with the numbers 0 through to n-1, where n is the length of the shortest iterable supplied to the function.

The code

g = ((names[i], heroes[i]) for i in shortest_seq(names, heroes))
for item in g:
    print(item)

Will perform the same as

for item in zip(names, heroes)
    print item
Yngve Moe
  • 1,057
  • 7
  • 17