簡體   English   中英

將值附加到python中的列表

[英]appending values to a list in python

我正在這樣做:

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
    allValues.append(line[theColumn-1])
  return list(set(allValues))

我在此行上的string index out of range

allValues.append(line[theColumn-1])

有人知道我在做什么錯嗎?

如果需要,這是完整的代碼:

import hashlib

def doStuff():
  createFiles('together.csv')

def readFile(fileName):
  a=open(fileName)
  fileContents=a.read()
  a.close()
  return fileContents

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
    allValues.append(line[theColumn-1])
  return list(set(allValues))

def createFiles(inputFile):
  inputFileText=readFile(inputFile)
  b = inputFileText.split('\n')
  r = readFile('header.txt')
  DISTINCTCOLUMN=12
  dValues = GetDistinctValues(inputFileText,DISTINCTCOLUMN)

  for uniqueValue in dValues:
    theHash=hashlib.sha224(uniqueValue).hexdigest()
    for x in b:
      if x[DISTINCTCOLUMN]==uniqueValue:
        x = x.replace(', ',',').decode('latin-1','ignore')
        y = x.split(',')
        if len(y) < 3:
          break
        elif len(y) > 3:
          desc = ' '.join(y[3:])
        else:
          desc = 'No description'
        # Replacing non-XML-allowed characters here (add more if needed)
        y[2] = y[2].replace('&','&amp;')

        desc = desc.replace('&','&amp;')

        r += '\n<Placemark><name>'+y[2].encode('utf-8','xmlcharrefreplace')+'</name>' \
          '\n<description>'+desc.encode('utf-8','xmlcharrefreplace')+'</description>\n' \
          '<Point><coordinates>'+y[0]+','+y[1]+'</coordinates></Point>\n</Placemark>'
    r += readFile('footer.txt')
    f = open(theHash,'w')
    f.write(r)
    f.close()

之所以發生這種情況,是因為line沒有代碼假定的那么多元素。 請嘗試以下操作:

for line in lines:
    if len(line) < theColumn:
        print "This line doesn't have enough elements:\n" + line
    else:
        allValues.append(line[theColumn-1])
return list(set(allValues))

這將為您提供提示,這是嘗試訪問列表范圍之外的元素(即不存在的元素)時遇到的錯誤類型。

該錯誤不是由append()引起的,這是因為該line不夠長。 也許文件末尾有一個空行。 你可以試試

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
    if line:
      allValues.append(line[theColumn-1])
  return list(set(allValues))

否則,異常處理程序可以幫助查找問題所在

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
     try:
        allValues.append(line[theColumn-1])
     except IndexError:
        print "line: %r"%line
  return list(set(allValues))
line[theColumn-1])

如果將字符串(行)短接“ theColumn”,這當然會引起上述錯誤。 您還會期待什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM