Python- 我如何合并两个输出并合并它们以便打印出单个值? python 2.7
Python- How do I combine two outputs and merge them so what prints is a single value? python 2.7
所以基本上我有这个代码:
try:
fhanddate = open('AAPLprice.txt')
except:
print 'Could not open file - closing application'
exit()
stock_date = []
for line in fhanddate:
p = line.strip()
q = p.split(',')
r = q[0:]
stock_date.append(r)
for line in stock_date:
pass
last = line
print last[0]
try:
fhanda = open('AAPLprice.txt')
except:
print 'Could not open file - closing application'
exit()
stock_priceA = []
for line in fhanda:
p = line.strip()
q = p.split(',')
r = q[-1:]
stock_priceA.append(r)
print max(stock_priceA)
我的输出结果是:
2015-07-21
['129.606052']
所以我想知道如何组合这两个输出,结果是:2015-07-21 129.606052
当我尝试将它们组合起来时,出现 "TypeError: cannot concatenate 'str' and 'list' objects" 错误
您可以简单地用“+”将它们连接在一起:
a = 2015-07-21
b = ['129.606052']
print a + b[0]
b[0]
取列表中的第一项,b
。在本例中,它取出列表中的唯一项。您可以通过简单地在它们之间添加一个字符串来添加 space:
print a + " " + b[0]
所以基本上我有这个代码:
try:
fhanddate = open('AAPLprice.txt')
except:
print 'Could not open file - closing application'
exit()
stock_date = []
for line in fhanddate:
p = line.strip()
q = p.split(',')
r = q[0:]
stock_date.append(r)
for line in stock_date:
pass
last = line
print last[0]
try:
fhanda = open('AAPLprice.txt')
except:
print 'Could not open file - closing application'
exit()
stock_priceA = []
for line in fhanda:
p = line.strip()
q = p.split(',')
r = q[-1:]
stock_priceA.append(r)
print max(stock_priceA)
我的输出结果是:
2015-07-21
['129.606052']
所以我想知道如何组合这两个输出,结果是:2015-07-21 129.606052
当我尝试将它们组合起来时,出现 "TypeError: cannot concatenate 'str' and 'list' objects" 错误
您可以简单地用“+”将它们连接在一起:
a = 2015-07-21
b = ['129.606052']
print a + b[0]
b[0]
取列表中的第一项,b
。在本例中,它取出列表中的唯一项。您可以通过简单地在它们之间添加一个字符串来添加 space:
print a + " " + b[0]