第五天代码学习

使用列表理解来将列表中的每个奇数平方。列表由逗号分隔的数字序列输入。

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转成列表)

此题关于map的解析

法二

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)

strip()用法

法三

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值