一
使用列表理解来将列表中的每个奇数平方。列表由逗号分隔的数字序列输入。
Question:
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. >Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,9,25,49,81
li=input().split(',')
out=[]
li=[int(i) for i in li]
for i in li:
if i%2!=0:
out.append(i*i)
out=[str(i) for i in out]
print(','.join(out))
注意输入:1,2,3,4,5(是字符串)
然后处理成列表 列表里面是 int()格式
for结束得到的是列表out[ ]
再将他‘像输入那样转换处理’ 处理成str格式,join ‘,’输出
二
*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*
total = 0
while True:
s = input().split()
if not s : # break if the string is empty
break
cm,num = map(str,s) # str是内置函数 two inputs are distributed in cm and num in string data type
if cm=='D':
total+=int(num)
else:
total-=int(num)
print(total)
注意 if not s 不可以写成if s == ""
map(map,s)在此处无用
cm,num = s # two inputs are distributed in cm and num in string data type
map的用法
Python3中map用法(需要加list转成列表)
法二
li=[]
while True:
x=input()
if not x:
break
li.append(x)# 输入先存进列表 每个类似‘D 200’都是整体
out=0
for i in li:
if 'D'in i: # 每个item判断里面是否含D
out+=int(i.strip('D ')) # 剔除‘D ’剩下部分int()化成数字
else:
out -= int(i.strip('W '))
print(out)
法三
out=0
while True:
x=input().split(" ") #每输入一个分割成列表的【0】 【1】两部分
if x[0]=="D": #判断
out+=int(x[1]) # 加减【1】部分的值,需要int换一下格式
elif x[0]=="W":
out-=int(x[1])
else:
break
print(out)