Python [int(x.strip())对于f中x的含义]
这里,我没有得到第二行x.strip for x in fstrip删除字符串开头和结尾的空格,结果转换为整数类型 例如:Python [int(x.strip())对于f中x的含义],python,Python,这里,我没有得到第二行x.strip for x in fstrip删除字符串开头和结尾的空格,结果转换为整数类型 例如: with open("input.txt") as f: l = [int(x.strip()) for x in f] for i, n1 in enumerate(l): for j, n2 in enumerate(l[i+1:]): if n1 + n2 == 2020: part1 =
with open("input.txt") as f:
l = [int(x.strip()) for x in f]
for i, n1 in enumerate(l):
for j, n2 in enumerate(l[i+1:]):
if n1 + n2 == 2020:
part1 = n1 * n2
for n3 in l[i+j+1:]:
if n1 + n2 + n3 == 2020:
part2 = n1 * n2 * n3
print(part1)
print(part2)
这是一种表达方式
它所做的是从文件句柄f中读取每一行,将该行存储在变量x中,去掉该行的前导和尾随空间,并将该行转换为int值
所有这些int值都收集到一个列表中,该列表被分配给l。阅读Python中的列表理解。strip方法删除尾随空格,int将尽可能将字符串转换为整数。例如,int 12.strip将返回12
string=" 123 "
print(int(string.strip()))
##prints 123