首页 > 解决方案 > 在一行python3中搜索追加和打印

问题描述

我有这样的数据:

ice_cream 0.00013286998380339406

hot_chocolate 0.0002134821993051205

ice_cream -7.833574001019025e-05

hot_chocolate -0.0001492061779651939

我想像这样打印出来:

ice_cream 0.00013286998380339406 -7.833574001019025e-05

hot_chocolate 0.0002134821993051205 -0.0001492061779651939

我尝试了一些东西,但不能正常工作。我怎样才能在python3中做到这一点?

标签: python-3.x

解决方案


最好的方法可能是为每个变量创建一个列表并将值附加到它。

# Creating the lists
ice_cream =[]
hot_chocolate = []

# Appending the values to the lists
# In practise you would use a loop here, that reads your source file and 
# then appends the value to the respective list
ice_cream.append(value1)
ice_cream.append(value2)

hot_chocolate.append(value3)
hot_chocolate.append(value4)

# printing out the values
print("ice_cream",ice_cream)
print("hot_chocolate",hot_chocolate)

它应该返回如下内容:

ice_cream [0.00013286998380339406, -7.833574001019025e-05]
hot_chocolate [0.0002134821993051205, -0.0001492061779651939]

如果输出没有方括号和逗号非常重要,您可以将列表转换为字符串,然后使用其他方法将其删除。

print("hot_chocolate", " ".join(hot_chocolate))

>>> hot_chocolate 0.0002134821993051205 -0.0001492061779651939

推荐阅读