首页 > 解决方案 > How to use the map() function correctly in python, with list?

问题描述

The code takes one input and I cannot understand how the variable arr works? It always outputs one value and for whatever the value of n is. The goal is to iterate n times and take the values in a list.

import math
import os
import random
import re
import sys




if __name__ == '__main__':
    n = int(input())

    arr = list(map(int, input().rstrip().split()))

标签: pythonpython-3.xlist

解决方案


That line of code to build an array is quite popular on HackerRank.

Let's break it down for you:

  1. list: A list is a simple array of homogeneous or heterogenous elements in python. More details: https://docs.python.org/3/tutorial/datastructures.html
  2. map: A map is a method which performs the given operation as first argument to the iterable provided as the second arg and returns an iterator. More information: https://docs.python.org/3/library/functions.html#map
  3. input: As the name says, waits for input from the STDIN until a newline is hit. More at : https://docs.python.org/3/library/functions.html#input
  4. rstrip: removes the trailing characters from the string. If not argument is provided, it removes trailing whitespaces. More at https://docs.python.org/3/library/stdtypes.html#str.rstrip
  5. split: Splits the given string into a list. If no sep argument is provided, it defaults to a whitespace. More at: https://docs.python.org/3/library/stdtypes.html#str.split

As now we know what each method does, here's what's happening with:

arr = list(map(int, input().rstrip().split()))
  1. There's a variable arr which is being assigned the value to the statement on the right.

  2. On the right, the data is being fetched using the input method, followed by stripping off the trailing spaces and splitting the input to a list with whitespace as the separator. This is helpful in cases when the input is given on a single line, separated by spaces. for e.g. 22 34 12 343 12 42 . Though, since the split would return a list of str as input feeds this as str, we need to convert each element of this list to an int to process them for our program.

  3. And that where map comes into play. We would use the int function to convert the list of str to list of int. And since map returns an iterator, we would convert that to a list.

>>> mydata = input()
22 34 12 343 12 42
>>> mydata.strip()
'22 34 12 343 12 42'
>>> mydata.strip().split()
['22', '34', '12', '343', '12', '42']
>>> map(int, mydata.strip().split())
<map object at 0x10d8a4a00>
>>> list(map(int, mydata.strip().split()))
[22, 34, 12, 343, 12, 42]
>>> arr = list(map(int, mydata.strip().split()))
>>> arr
[22, 34, 12, 343, 12, 42]

# Summarising it with mydata replaced back with input
>>> arr = list(map(int, input().strip().split()))
22 34 12 343 12 42
>>> arr
[22, 34, 12, 343, 12, 42]

推荐阅读