如何使用输入csv文件索引和自动处理列表

时间:2011-03-08 01:53:14

标签: python csv

3 个答案:

答案 0 :(得分:3)

好吧,我希望你能成功解决问题。

您是否找到了如何在值中使用'.'进行管理?这很简单:

replace('.','')

对我来说,我认为以下代码符合所有要求。我希望这不是一个功课,你学到了一些东西。

import csv
import random
from sys import exit

with open('heights.csv','rb') as f:
    names,a = {},{}
    for k,row in enumerate(csv.reader(f)):
        names[k] = row[0]
        a[k]     = int(row[1].replace('.',''))
    print names
    print 'a==',a
    L = len(a)

compute = input(">")

if compute == 1:

    if a[1] - a[0] <= 1000 and all(a[i] - a[i-1] <= 2300 for i in xrange(2,L)):

        read_b = {L-1 : random.randint( max(500,a[1]-a[0]), 1000 ) }
        read_a = {1   : a[0] + read_b[L-1] - a[1] }

        for i in xrange(2,L):
            read_b[L-i] = random.randint( max(500,a[i]-a[i-1]), 2300 )
            read_a[i] = a[i-1] + read_b[L-i] - a[i]

    else:
        exit("The file can't be treated because of the relative values of "
             "the following couples of lines : "+\
             ('(0,1) ' if 1000 < a[1] - a[0] else "")+\
             ' '.join(repr((i-1,i)) for i in xrange(2,L) if 2300 < a[i] - a[i-1]))



    with open('output.txt','w') as fw:
        fw.write('[1]\n1={}\n4={}\n\n[2]\n1={}\n4={}\n\n'.\
                 format(names[0],read_b[L-1],names[1],read_a[1]))

        fw.writelines('[{}]\n1=\n4={}\n\n[{}]\n1={}\n4={}\n\n'.\
                      format(str(2*k-1),read_b[L-k],str(2*k),names[k],read_a[k])
                      for k in xrange(2,L))                           



    # display of the execution

    print 'read_a== %s\nread_b== %s\n\n' % (read_a,read_b)+\
          ''+\
          ('\n'.join(('  a[%s] ========== %s ******' % (y,a[y])+\
                      '\n    +read_b[%s] == %s' % (str(L-y-1), read_b[L-y-1])+\
                      '\n    -read_a[%s] == %s' % (str(y+1)  ,-read_a[y+1]  ) )
                     for y in xrange(L-1)) )+\
          '\n  a[%s] ========== %s ******\n\n' % (L-1,a[L-1])+\
          ''+\
          ('\n'.join(('  a[%s] ========== %s ******' % (y,a[y])+\
                      '\n    +read_a[%s] == %s' % (y  , read_a[y]  )+\
                      '\n    -read_b[%s] == %s' % (L-y,-read_b[L-y]) )
                     for y in xrange(L-1,0,-1)) )+\
          '\n  a[%s] ========== %s ******\n\n' % (0,a[0])+\
          ''+\
          'sum(read_a.values())== %s\nsum(read_b.values())== %s' %\
          (sum(read_a.values()),sum(read_b.values()))

说明:

read_b 变量的值由randint()创建。如果每个randint()中的边界被认为是不可触及的约束,那么正面的条件就是 read_a 变量的值。

您写道:

read_0a = random.randint(500,1000)  
read_1a = a[0] + read_0a - a[1]

就是说

read_a[0] = random.randint(500,1000)  
read_a[1] = a[0] + read_a[0] - a[1]
# nota bene: read_a[0] is in fact read_b[len(a)-1]

条件 0&lt; = read_a [1] 仅在 0&lt; = a [0] + read_a [0] - a [1] <时验证/ p>

也就是说 a [1] - a [0]&lt; = read_a [0] (E)

所以,有3个案例:

  • 如果 a [1] - a [0]&lt; = 500 为True,则对于任何值 read_a [0] 由read_a[0] = random.randint(500,1000)

  • 定义
  • 如果 500&lt; = a [1] - a [0]&lt; = 1000 为真,则(E)仅对值 read_a [0]为真read_a[0] = random.randint(a[1] - a[0] ,1000)

  • 定义
  • 如果 1000&lt; a [1] - a [0] 为True,不可能找到介于500和1000之间的值为 read_a [0] 的值,因此 read_a [1] 将是积极的。

read_a [0] 的值尊重条件 read_a [1]&gt;之前,我们可能会考虑重复说明read_a[0] = random.randint(500,1000)的说明read_b[len(a)-1] = random.randint(500,1000) ; = 0

但是如果 1000&lt; a [1] - a [0] ,会有无限循环。这意味着文件中的值不能是没有条件的任何整数:它们必须验证某些条件,以便所有 read_a 值都为正。我在代码中验证了这个条件。

read_a 中带边界的其他值

randint(500,2300)

答案 1 :(得分:1)

import csv
import random

with open('fofo.txt','rb') as f:
    rd = csv.reader(f)
    a = [int(row[1]) for row in rd]
    print 'a==',a

(.... to be continued by daikini's code...)

rd = csv.reader(f)是一个迭代器,它在使用rd.next()或在for循环期间返回时返回csv文件的一行。 必须以读取二进制模式'rb'

打开文件

将项目放在列表a中,只需按列表索引对它们进行索引。

以下代码已被编辑:

- 我在a[len(a)-1]

的定义中使用a[len(a)-i]更正了read_b

- 我将random.randint(500,2300)放在R

定义中的read_a列表中

- 按read_a[0]定义read_a[0] = a[1] + read_a[1] - a[0]没有实际意义。实际上read_a[0]正是R[0]。我删除了这一行

- 事实上,也可以定义read_b[3]。事实证明是read_a[0];因此R[0]==read_a[0]==read_b[3]! -

import csv
import random

with open('heights.csv','rb') as f:
    a = [int(row[1]) for row in csv.reader(f)]
    print 'a==',a

compute = input(">")
if compute == 1:

    R = [random.randint(500,2300) for j in xrange(len(a)-1)]

    read_a = dict((i+1,a[i] + R[i] - a[i+1])
                  for i in xrange(0,len(a)-1) )

    read_b = dict( (i, a[len(a)-i] + read_a[len(a)-i] - a[len(a)-i-1])
                   for i in xrange(1,len(a)))




    print 'R==',R
    print 'read_a==',read_a
    print 'read_b==',read_b
    print

    for y in xrange(len(a)-1):
        print '  a[%s] ========== %s ******' % (y,a[y])
        print '      +R[%s]    == %s' % (str(y),R[y])
        print '    -read_a[%s] == %s' % (str(y+1),-read_a[y+1])
    print '  a[%s] ========== %s ******' % (len(a)-1,a[len(a)-1])
    print '\n'

    #print ' a['+str(len(a)-1)+']==',a[len(a)-1]
    for y in xrange(len(a)-1,0,-1):
        print '  a[%s] ========== %s ******' % (y,a[y])
        print '    +read_a[%s] == %s' % (y,read_a[y])
        print '    -read_b[%s] == %s' % (len(a)-y,-read_b[len(a)-y])
    print '  a[%s] ========== %s ******' % (0,a[0])
    print '\n'

    print 'sum(read_a.values())==',sum(read_a.values())
    print 'sum(read_b.values())===',sum(read_b.values())

最后,我们注意到read_b.values() = R[::-1]然后代码可以简化为:

import csv
import random

with open('heights.csv','rb') as f:
    a = [int(row[1]) for row in csv.reader(f)]
    print 'a==',a

compute = input(">")

if compute == 1:

    read_b = dict((j+1,random.randint(500,2300)) for j in xrange(len(a)-1))

    read_a = dict((i,a[i-1] + read_b[len(a)-i] - a[i])
                  for i in xrange(1,len(a)) )



    print 'read_a==',read_a
    print 'read_b==',read_b
    print

    for y in xrange(len(a)-1):
        print '  a[%s] ========== %s ******' % (y,a[y])
        print '    +read_b[%s] == %s' % (str(len(a)-y-1),read_b[len(a)-y-1])
        print '    -read_a[%s] == %s' % (str(y+1),-read_a[y+1])
    print '  a[%s] ========== %s ******' % (len(a)-1,a[len(a)-1])
    print '\n'

    for y in xrange(len(a)-1,0,-1):
        print '  a[%s] ========== %s ******' % (y,a[y])
        print '    +read_a[%s] == %s' % (y,read_a[y])
        print '    -read_b[%s] == %s' % (len(a)-y,-read_b[len(a)-y])
    print '  a[%s] ========== %s ******' % (0,a[0])
    print '\n'

    print 'sum(read_a.values())==',sum(read_a.values())
    print 'sum(read_b.values())==',sum(read_b.values())

这些代码可用于任意数量的行&gt; = 2

关于正数的条件:

read_b中的数字是第一个被计算的数字。所以我搜索使read_b始终为正的条件:

  

因为read_a [i] = a [i-1] +   read_b [len(a)-i] - a [i]

     

=&GT; read_b [len(a)-i] = read_a [i] + a [i] - a [i-1]

     

=&GT; read_b [j] = read_a [len(a)-j] + a [len(a)-j] - a [len(a)-j-1]

因为我们必须有0&lt; read_a [len(a)-j]

  

=&GT; a [len(a)-j] - a [len(a)-j-1]&lt; read_a [len(a)-j] + a [len(a)-j] -   a [len(a)-j-1]

     

=&GT; a [len(a)-j] - a [len(a)-j-1]&lt; read_b [j]

     

=&GT;我们必须有[len(a)-j] - [len(a)-j-1] + 1&lt; = read_b [j]

然后条件

max(a[len(a)-j] - a[len(a)-j-1]  + 1 , 500))  <= read_b[j] 

我是对的吗?

答案 2 :(得分:1)

from random import randint

compute = input(">")

if compute == 1:

    # If you have to store it anyway, might as well go whole-hog:
    vals = [int(l.split(",")[1]) for l in open("heights.csv").readlines()]

    reads[0] = vals[0] + randint(500, 1000)
    for i in xrange(len(vals) - 1):
        reads.append(vals[i-1] + randint(500, 1000) - vals[i])
        # not sure what to do with the last value