从列表中删除花括号和单引号

时间:2020-05-12 12:11:42

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

这似乎在几种不同的情况下被问到,但是每次我应用一个时,似乎都不会对我的输出产生影响。

目标:我有一个要加载到列表中的CSV文件,然后能够操纵这些值-与其他值进行比较。

程序概述:我编写了一个程序来识别素数。如果找到一个,我将其保存到文件中并添加一盏灯。如果我重新启动程序,它将查找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)

3 个答案:

答案 0 :(得分:1)

这可能有帮助:

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

答案 1 :(得分:0)

您可以使用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']]

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

答案 2 :(得分:0)

以下是其他信息:

问题似乎与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

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