List Manipulation

B

Bruno Desthuilliers

Mike Kent wrote:
(snip)
p[j] does not give you a reference to an element inside p.

Yes it does:
a = ['a']
b = ['b']
c = ['c']
p = [a, b, c]
p[0] is a True
p[1] is b True
p[2] is c True
p[0].append('z')
a ['a', 'z']

It gives
you a new sublist containing one element from p.

Plain wrong.
You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Plain wrong.
Try doing:

p[j] = p[j].append(col)

Plain wrong again. list.append() returns None, so the following code:
- retrieve a reference to p[j] (which happens to be a list)
- append something to that list
- then rebind p[j] to None...
However, this will still result in inefficient code.

Indeed. One could even say "broken" and "braindead".
Since every line
you read in via the csv reader is already a list, try this (untested)

Given your obvious lack of even the most basic knowledge concerning
Python, it would be better for you *and everyone reading this newsgroup*
that you take time to actually test before posting.
 
G

Gerard Flanagan

Roman said:
Dennis said:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:
It would help if you gave a sample of the input data (three lines
worth, say) AND an example of what the final output should be from those
three lines.
for col in line:
p[:0].append(str(col))

As has been pointed out, as soon as you used the [:0], you created a
local/temporary EMPTY slice of the original P, and you are appending one
column's value to this temporary, which is then thrown away.
import csv

-=-=-=-=-=-=-=- PROGRAM
p = []

fin = open("firearms.csv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter=",")

for line in [reader.next() for i in range(7)]:
p.append(line)

fin.close()
print p
-=-=-=-=-=-=-=- OUTPUT
[['Category', 'Model', 'Caliber', 'Serial #', 'Description',
'Accessories'], ['Air', 'Daisy 717 Pistol', '.177 pellet', '', '', ''],
['Air', 'Daisy/NRA PowerLine 953 Rifle', '.177 pellet', 'n/a',
'Micrometer Peep, "Globe" front (missing alternate inserts', 'Shooting
sling'], ['Air', 'RWS Diana Model 54 "Air King" Rifle', '.22 pellet',
'4022395', 'Hunting grade - >900fps', '2-7x BSA AOL scope'], ['Air',
'Gamo/NRA', '0.177', '', 'Hunting grade - ~1000fps; NRA markings on
barrel, stock', '4x (BSA?) AOL scope, NRA badge'], ['Air',
'Walther/Crossman CP99 Pistol', '.177 pellet', '', 'CO2, repeater
(currently magazine jams trigger/safety)', ''], ['Percussion', '? New
Orleans Ace boot-pistol', '.36 lead', '', '', '']]
-=-=-=-=-=-=-=- INPUT (just first seven lines)
Category,Model,Caliber,Serial #,Description,Accessories
Air,Daisy 717 Pistol,.177 pellet,,,
Air,Daisy/NRA PowerLine 953 Rifle,.177 pellet,n/a,"Micrometer Peep,
""Globe"" front (missing alternate inserts",Shooting sling
Air,"RWS Diana Model 54 ""Air King"" Rifle",.22 pellet,4022395,Hunting
grade - >900fps,2-7x BSA AOL scope
Air,Gamo/NRA,0.177,,"Hunting grade - ~1000fps; NRA markings on barrel,
stock","4x (BSA?) AOL scope, NRA badge"
Air,Walther/Crossman CP99 Pistol,.177 pellet,,"CO2, repeater (currently
magazine jams trigger/safety)",
Percussion,? New Orleans Ace boot-pistol,.36 lead,,,



But your explanations are unclear... Maybe you wanted the first
sublist to be all the first column, etc.

-=-=-=-=-=-=-=- PROGRAM
import csv

p = None

fin = open("firearms.csv", "r")
reader = csv.reader(fin, dialect="excel", quotechar='"', delimiter=",")

for line in [reader.next() for i in range(7)]:
if not p:
p = [[] for j in range(len(line))]
for c in range(len(line)):
p[c].append(line[c])

fin.close()
print p
-=-=-=-=-=-=-=- OUTPUT (same input)
[['Category', 'Air', 'Air', 'Air', 'Air', 'Air', 'Percussion'],
['Model', 'Daisy 717 Pistol', 'Daisy/NRA PowerLine 953 Rifle', 'RWS
Diana Model 54 "Air King" Rifle', 'Gamo/NRA', 'Walther/Crossman CP99
Pistol', '? New Orleans Ace boot-pistol'], ['Caliber', '.177 pellet',
'.177 pellet', '.22 pellet', '0.177', '.177 pellet', '.36 lead'],
['Serial #', '', 'n/a', '4022395', '', '', ''], ['Description', '',
'Micrometer Peep, "Globe" front (missing alternate inserts', 'Hunting
grade - >900fps', 'Hunting grade - ~1000fps; NRA markings on barrel,
stock', 'CO2, repeater (currently magazine jams trigger/safety)', ''],
['Accessories', '', 'Shooting sling', '2-7x BSA AOL scope', '4x (BSA?)
AOL scope, NRA badge', '', '']]
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/

below is the data I am trying to read

"000004" "AS0042123BO" "AS 0042.123 ROYAL ELONG SEAT
BO" "001610" "A/S Fixtures" 0 $99.00 3.70 "" "0042123" 11/20/2003
"000024" "AS0042001BK" "AS 0042.001 ROYAL EL*DISC BY
MFG*BK" "001610" "A/S
Fixtures" 0 $99.00 8.00 "723085611663" "0042001" 11/20/2003
"000104" "CH130TTWH" "CH 130TT EL PLAS SEAT C/F W/C
WH" "207067" "Church Seats" 12 $25.00 6.75 "073088079961" "130TT
000" 12/28/1995
[...]

[Fixed top-posting]

You can use a class rather than have lists of lists:

-------------------------------------
print

data = '''
id,category_id,description,price
0024,A1,cup,1.00
0025,A1,saucer,2.00
0026,A1,teapot,5.00'''

class MyClass(object):
id = None
category_id = None
description = None
price = None

def __init__(self, id=None, category_id=None, description=None,
price=None):
self.id = id
self.category_id = category_id
self.description = description
self.price = price

def __str__(self):
return '%s - %s' % (self.id,self.description)

myclass_collection = []

import csv

reader = csv.reader( data.splitlines()[1:] )

firstline = reader.next()

for line in reader:
names_and_values = dict(zip(firstline,line))
c = MyClass(**names_and_values)
myclass_collection.append( c )

for item in myclass_collection:
print item
 
G

Gerard Flanagan

Dennis said:
Are you sure you want to introduce classes into the mix, when simple
basics are still causing so many problems? <G>
--

I thought it lessened the complexity, but yes, good point :)

Gerard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,281
Latest member
Pedroaciny

Latest Threads

Top