【问题标题】:Search append and print in one line python3在一行python3中搜索追加和打印
【发布时间】:2019-09-01 08:00:11
【问题描述】:

我有这样的数据:

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 中做到这一点?

【问题讨论】:

  • 到目前为止你尝试了什么?请向我们展示您的代码,以便我们查看它以找到您的问题。
  • 输入格式是什么——pandas、list、dict?
  • 输入数据的来源是什么?

标签: python-3.x


【解决方案1】:

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

# 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

【讨论】:

    【解决方案2】:
    data = open("combine.txt", 'r')
    dic ={}
    for line in data.readlines():
        line=line.strip("\n")
        if line:
            key,value = line.split(" ")
            if key in dic:
                dic[key].append(value)
            else:
                dic[key]=[]
                dic[key].append(value)
    for k in dic.keys():
        print(str(k)," ".join(dic[k]))
    data.close()
    

    如果您的输入是文本文件,这就是您的问题的解决方案,希望它对您有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 2017-09-24
      • 2015-04-17
      相关资源
      最近更新 更多