我的数据格式如下:
XX, 4059
TSD, 109
ETC, 3679
我想返回类似以下的内容:
[('XX', 4095), ('TSD', 109),..]
如何获取2列列表,从每行中创建一个元组,将所有元组放入列表中,然后返回该列表?我正在使用PyCharm。
请不要字典。
def initilize_portfolio(filename):
data = open("holdings.txt", "r") # opens portfolio and reads it
port_list = []
for line in data:
new_line = filename.readline().rstrip('\r\n')
port_list.append(new_line)
return(port_list.append)
我需要在某个地方制作一个元组,不知道该怎么做。
该代码片段完成了您要实现的目标
port_list = []
with open("holdings.txt") as filename:
for line in filename:
# strip removes all leading and trailing spaces
line = line.strip()
# skip empty lines
if not line:
continue
# use partition to split the entries
a, _, b = line.partition(',')
a = a.strip()
b = int(b.strip())
# create a tuple while appending
port_list.append((a, b))
print(port_list)
您可以将其放在函数中并返回列表,而不是打印它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句