Python创建任意数量的列表来存储列中的所有值

2024-05-18 19:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有csv文件,其中的列数不是常量。对于每个列,我尝试将该列中的所有值存储到一个单独的列表中,以便可以计算重复出现的值的数量。我已经编写了一些代码来实现这一点,但是它似乎并不能很好地将append放入一个列表中。在

示例输入是love hurt hit。 我的输入是一个具有可变行数和可变列数的csv文件。它一直在为另一个csv文件而改变。假设一个文件有3列,下一个文件有20列。“是”和“否”是在所有这些列下显示的值。这些值的出现是随机的。我要做的是提取每个单独列中的所有值,并将它们附加到一个列表中。因此,一旦我退出for循环,理想情况下我希望看到给定列中的所有值;而不是最后一个值,也不是每个值都打印在另一个下面。在

当我追加所有值时,它应该是['love', 'yes' 'no', 'yes' ......],其中yes和{}是{}列下的值。 相反,我将每个值打印在新行上,例如:

['love']

['yes']

。。。。在

这就是我目前所拥有的。请帮忙!在

a,b,c = [],[],[]
headings = []
allCols = []

def getColCount(currLine):
    return len(currLine)    

# Open the file and read it
with open(filename1, 'r') as f1:

 csvlines = csv.reader(f1, delimiter=',')

 for lineNum, line in enumerate(csvlines):
      colCount = getColCount(line)               
      allCols = [[] for x in range(0, colCount)]         

      a.append(line[0])            # this prints like I want it to - in series

      for i in range(0, colCount):

           allCols[i].append(line[i])   # this doesn't

      print ','.join(allCols[2])

Tags: 文件csvin列表forlineityes
3条回答

您需要做的是将行拆分为每个单词的数组,然后将其添加到列表中。假设这是你的档案数据.csv'. 在

您可以使用以下命令读取文件:

finalData = []
fileHandler = open('data.csv', r)
#Read the lines from the file
for line in fileHandler.readlines():
    #Split the line by comma
    lineArr = line.split(',')
    for i in range(len(lineArr)):
        #Strip any whitespace from the lines
        lineArr[i] = lineArr[i].replace(" ", "")
    #Add the data to the final array
    finalData.append(lineArr)

这是一个非常简单的方法来做你需要的。在

另一种方法是利用熊猫。它的read_csv功能应该直接将其拆分为列,然后从那里进行总结应该很简单(集合。计数器在每个列上)。在

如果要交换行和列,zip很有用。一个简单的例子:

>>> data = [["a", "b", "c"], # header row
            [1, 2, 3], # data rows
            [4, 5, 6], 
            [7, 8, 9]]
>>> swap = list(zip(*data))
>>> print(swap)
[('a', 1, 4, 7), # first column
 ('b', 2, 5, 8), # second column
 ('c', 3, 6, 9)] # third column

请注意,根据the docs

The returned list is truncated in length to the length of the shortest argument sequence.

相关问题 更多 >

    热门问题