【问题标题】:Assigning every other word in the list to be printed in python分配列表中的每个其他单词以在 python 中打印
【发布时间】:2021-06-24 00:16:46
【问题描述】:

我正在阅读一个文件,其中只有第 1 列和第 3 列是我感兴趣的。在收集第一列的时间戳和第三列的产品名称并将数据存储在列表中之后,我打算打印一条消息:“产品 Y 的时间戳 X”。以下是我现在拥有的:

def reading_file():
    file_reading = open("marjoja.txt", "r", encoding="utf-8") 
    # removing the header
    file_reading.readline()
    products = []
    while (True):
        row = file_reading.readline() 
        if len(row) == 0: 
            break
        else:
            # collecting data from 1 and 3 columns
            lines = row.split(';')[0::2]
            #products.append(row.split(';')[0::2])
            products.extend(lines)
    file_reading.close()
    return products

def main():
    products = reading_file()
    product_lst = str(products).split("\n")
    for lines in product_lst:
        if lines == "0":
            break
        else:
            print("Time", lines.split()[1], "on product", lines.split()[0],".")
  

main()

print(products) 的输出将是:['jordans', '00:00\n', 'polish', '02:13\n']。我想主要制作的是-“乔丹的时间00:00”。我正在生成的是:“['jordans', 的时间'00:00\n'。我如何将列表中的单词分配到正确的位置?

【问题讨论】:

  • 您正在处理文件的每隔一行。将removing the header 部分移到循环之前。

标签: python for-loop split


【解决方案1】:

阅读时使用strip() 删除换行符。

返回列表列表,而不是将products 扩展为平面列表。那你就不用把products转成字符串再拆分了。

def reading_file():
    products = []

    with open("marjoja.txt", "r", encoding="utf-8") as file_reading:
        # removing the header
        file_reading.readline()

        for row in file_reading:
            row = row.strip()
            # collecting data from 1 and 3 columns
            lines = row.split(';')[0::2]
            products.append(lines)

    return products

def main():
    products = reading_file()
    for (product, time) in product_lst:
        print(f"Time {time} for product {product}.")
  
main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    相关资源
    最近更新 更多