【问题标题】:Removing brackts and single quotes from list从列表中删除括号和单引号
【发布时间】:2020-05-12 12:11:42
【问题描述】:

这似乎在几种不同的场景中被问到,但每次我应用一个时,它似乎对我的输出没有影响。

目标:我有一个 csv 文件,我想将其加载到列表中,然后能够操作这些值 - 与其他值进行比较等。

程序概述:我编写了一个程序来识别素数。如果我找到一个,我将它保存到一个文件中并附加一个 lit。如果我重新启动程序,它会查找 csv,将内容加载到列表中,然后从列表中的最后一个数字开始处理

问题:当我将文件加载到列表中时(素数)。它加载得很好,但我认为它最终成为一个嵌套列表。当我打印列表进行确认时,输出如下:

The csv file was loaded 
The list consists of: [['2'], ['3'], ['5']]
The highest prime is ['5']

当我试图操纵它们的值时,列表的内容稍后会在程序中引发错误 - 错误消息是 "TypeError: not all arguments converted during string formatting"

(对不起,如果这是 TMI)

这是加载 csv 的代码 - 有什么想法吗?

if os.path.isfile(primePath) is True:

    with open(os.path.join(primePath), newline='') as add2list:

        hold = csv.reader (add2list, delimiter=',')
        for row in hold:
            prime.append(row)
        candidate=prime[-1]
        print ("The csv file was loaded")
        print ("The list consists of:", prime)
        print ("The highest prime is", candidate)

【问题讨论】:

  • 你的问题是什么??
  • 文件的内容(实际数据,不是描述)是什么?

标签: python python-3.x list csv brackets


【解决方案1】:

这可能会有所帮助:

>>> a = [['2'], ['3'], ['5']]
>>> b = [int(i[0]) for i in a]
>>> b
[2, 3, 5]
>>> 

【讨论】:

  • 我试过这个,它似乎有帮助......虽然,我可能没有正确写下这一行:with open(os.path.join(primePath), newline='') as add2list: hold = csv.reader (add2list, delimiter=',') for row in hold: row=[int(i[0]) for i in hold] prime.append(row) Candidate=prime[-1] 输出为:已加载 csv 文件列表包括: [[3, 5]] 最高质数为 [3, 5]
  • @FredtheWhale 你在说什么?你能说得更具体点吗?
【解决方案2】:

您可以使用ast.literal_eval 安全地解析此列表:

>>> from ast import literal_eval
>>> for line in open('file.txt', 'r'):
...     result = int(literal_eval(line)[0][-1])
... 
>>> result
5

file.txt 的样子

[['2', '3', '5']]

显然您可以实现一些更好的错误处理,但这为您提供了一个开始。

【讨论】:

  • 对不起。无法上班。一堆乱七八糟的错误。 from ast import literal_eval with open(os.path.join(primePath), newline='') as add2list: hold = csv.reader (add2list, delimiter=',') for row in hold: result=int(literal_eval(hold )[0][-1]) prime.append(result) 输出 Traceback(最近一次调用最后一次):文件“.\myTest.py”,第 65 行,在 result=int(literal_eval(hold),[ 0],[-1]) ... raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_csv.reader object at>
【解决方案3】:

这里是附加信息:

问题似乎与 prime.append(row) 以及 csv.reader 如何从 csv 文件中提取信息有关。

当我在记事本中打开 csv 文件时,文件为: 2 3 5

当我第一次编写程序时,我让它将所有内容发布到一个文本文件中,并用逗号分隔。大约 5000 万,线路变得太长,它崩溃了。我正在尝试重写程序以发布到 csv 并垂直附加数字(如记事本示例中)

这是我目前拥有的完整程序:

#!/bin/python3

import time
import os
import csv

i=1
candidate=5
startRows = (2,3,5)
prime = []

folderLocation = "c:/notNow/"    

primeName = "primeNumbers.csv"

primePath=folderLocation + primeName

#check to see if the destination folder has been created
if os.path.isdir(folderLocation) is False:

    # if false, create the folder
    os.makedirs(folderLocation)
    print ("The directory was created")

else:
    print ("The directory exists")


# check to see if the prime file has been created
if os.path.isfile(primePath) is True:
    # if the prime file exists, load it
    # candidate will retain the highest value
    # and that's where the testing will start
    with open(os.path.join(primePath), newline='') as add2list:
        hold = csv.reader (add2list, delimiter=',')
        for row in hold:
            # remove the outer section of brackets from the csv input
            row="".join(row)
            prime.append(row)
        candidate=prime[-1]
        print ("The csv file was loaded")
        print ("The list consists of:", prime)
        print ("The highest prime is", candidate)
        time.sleep(1)

else:

    # Create and populate the prime file

    f = open(primePath, "w", newline = '')
    writer = csv.writer(f)
    for x in startRows:
        writer.writerow([x])
        prime.append(x)

    print ("The file was created and populated")
    candidate=prime[-1]
    print ("The highest prime is", candidate)
    time.sleep(1)

    candidate = prime[-2]
    print ("The list consists of:", prime )
    time.sleep(1)


while i > 0:

    i = 1
    x = "True"

    print ("this has been reset")
    print ("i=",i)
    print ("x=",x)
    print ("end of reset message")
    print ("")
    time.sleep(1)


    while x=="True": 
        print ("candidate is", candidate)
        print ("prime to test is", prime[i])
        time.sleep(1)


        print(candidate,"/", prime[i],"=",candidate%prime[i])



        # % (aka modulo) returns the remainder from a division
        if candidate%prime[i] == 0:
            print ("candidate is not prime -->", candidate)
            candidate+=2
            x = "False"

        # increment the counter
        i+=1


        # test for end of the array
        # if this is the end of the array then candidate is prime
        try:    
            test=prime[i]   
            # open the file in append mode

        except:

            with open(os.path.join(primePath), "a") as add2file:
                csv_writer = writer(add2file)
                csv_writer.writerow(str(candidate))
            print ("PRIME IDENTIFIED --->", candidate)

            prime.append(candidate)
            print("ARRAY HAS BEEN UPDATED WITH", candidate)         

            x="False"
            candidate+=2

当我运行它时,我得到以下输出:

The directory exists
The csv file was loaded
The list consists of: ['2', '3', '5']
The highest prime is 5
this has been reset
i= 1
x= True
end of reset message

candidate is 5
prime to test is 3
Traceback (most recent call last):
  File ".\primeNumberTest.py", line 86, in <module>
    print(candidate,"/", prime[i],"=",candidate%prime[i])
TypeError: not all arguments converted during string formatting

感谢您的关注和帮助。我认识到代码中可能存在其他问题。我很高兴/愿意自己解决这些问题。我似乎无法弄清楚这个问题,因为正在输入的数据无法使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多