Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

python 3.x - Inner workings of map() in a specific parsing situation

I know there are already at least two topics that explain how map() works but I can't seem to understand its workings in a specific case I encountered.

I was working on the following Python exercise:

Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:

D 100
W 200

D means deposit while W means withdrawal. Suppose the following input is supplied to the program:

D 300
D 300
W 200
D 100

Then, the output should be:

500

One of the answers offered for this exercise was the following:

total = 0
while True:
    s = input().split()
    if not s:
        break
    cm,num = map(str,s)

    if cm=='D':
        total+=int(num)
    if cm=='W':
        total-=int(num)

print(total)

Now, I understand that map applies a function (str) to an iterable (s), but what I'm failing to see is how the program identifies what is a number in the s string. I assume str converts each letter/number/etc in a string type, but then how does int(num) know what to pick as a whole number? In other words, how come this code doesn't produce some kind of TypeError or ValueError, because the way I see it, it would try and make an integer of (for example) "D 100"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

first

cm,num = map(str,s)

could be simplified as

cm,num = s

since s is already a list of strings made of 2 elements (if the input is correct). No need to convert strings that are already strings. s is just unpacked into 2 variables.

the way I see it, it would try and make an integer of (for example) "D 100"?

no it cannot, since num is the second parameter of the string.

if input is "D 100", then s is ['D','100'], then cm is 'D' and num is '100'

Then since num represents an integer int(num) is going to convert num to its integer value.

The above code is completely devoid of error checking (number of parameters, parameters "type") but with the correct parameters it works.

and map is completely useless in that particular example too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...