By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,766 Members | 1,340 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,766 IT Pros & Developers. It's quick & easy.

List Manipulation

P: n/a
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
p[:0].append(str(col))
cnt = cnt + 1

print p

when I change it to the following, I get rows back

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
print col
cnt = cnt + 1

print p
Thanks in advance

Jul 4 '06 #1
Share this Question
Share on Google+
19 Replies


P: n/a
Roman wrote:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
p[:0].append(str(col))
cnt = cnt + 1

print p
I'm having trouble deciding what you *intend* this program to do. It
looks like you want to take the first 7 lines of the input file, and
append all the data elements in those lines into one long list. If
that's what you want to do, then you are almost there, although you
could have written it better. If that's NOT what you want to do...
well, there are tutorials.

The problem with this code is in the line 'p[:0].append(str(col)).
Given a list p, p[:0] will give you the part of p *prior* to element 0.
Since there is never anything in a list prior to element 0, you will
always get an empty list back.

I assume this is not what you intended. But just *what* do you intend?
I sure can't say.

Jul 4 '06 #2

P: n/a

Roman wrote:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
p[:0].append(str(col))
What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert
Iain

Jul 4 '06 #3

P: n/a
Roman írta:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
p[:0].append(str(col))
You are appending to a slice. In that case, p[:0] creates a new list
object. You are not appending to p but to a new object (created from a
slice).
If you need to insert an item at the begining of a list, use the insert
method instead.
>>l = [2,3,4]
l.insert(1,0)
l
[2, 0, 3, 4]
Best,

Laszlo

Jul 4 '06 #4

P: n/a
On Tue, 04 Jul 2006 07:01:55 -0700, Roman wrote:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result
What do you mean? Does it print None?
cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
That's a very unPythonic way of doing the job. The usual way of doing
this would be something like this:

for line in reader[:7]:
# no need for the "if cnt 6: break" clause now

for col in line:
p[:0].append(str(col))
p[:0] creates a new list, which has a string appended to it, and is then
thrown away. What are you trying to do?

If you are trying to insert the new entry at the beginning of the list,
you probably want this:

p.insert(0, str(col))

Jul 4 '06 #5

P: n/a
Thanks for your help

My intention is to create matrix based on parsed csv file. So, I would
like to have a list of columns (which are also lists).

I have made the following changes and it still doesn't work.
cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1

print p

Iain King wrote:
Roman wrote:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
p[:0].append(str(col))

What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert
Iain
Jul 4 '06 #6

P: n/a
Roman schrieb:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
p[:0].append(str(col))
This is wrong. I'm not absolutely certain _what_ it does, but it doesn't
append anything to list p. p[:0] is an empty copy of p, you are
appending to this empty copy, not to p. What's wrong with
p.append(str(col))?
when I change it to the following, I get rows back

cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
for col in line:
print col
cnt = cnt + 1

print p
Here you print every single cell, but p doesn't change.

HTH
Koczian

--
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : Si*************@Bibliothek.Uni-Augsburg.DE
Jul 4 '06 #7

P: n/a
Roman wrote:
Thanks for your help

My intention is to create matrix based on parsed csv file. So, I would
like to have a list of columns (which are also lists).

I have made the following changes and it still doesn't work.
cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1

print p
p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Try doing:

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

However, this will still result in inefficient code. Since every line
you read in via the csv reader is already a list, try this (untested)
instead:

reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
p = [ line for line in reader[:7] ]

Jul 4 '06 #8

P: n/a
p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.
Not correct.

p = [[]]
p[0].append(1)
print p

yields

[[1]]

p[0] _gives_ you a reference to an object. If it is mutable (list are) and
append mutates it (it does), the code is perfectly alright.

I don't know what is "not working" for the OP, but actually his code works
if one replaces the csv-reading with a generated list:

cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = [["column_%i" % c for c in xrange(5)] for l in xrange(7)]
for line in reader:
if cnt 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1
print p
You are right of course that it is the most unpythonic way imaginabe to do
it. But it works.

Diez
Jul 4 '06 #9

P: n/a
Nothing got printed.

Could you tell me what would be pythonic version of what I am trying to
do?
Diez B. Roggisch wrote:
p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Not correct.

p = [[]]
p[0].append(1)
print p

yields

[[1]]

p[0] _gives_ you a reference to an object. If it is mutable (list are) and
append mutates it (it does), the code is perfectly alright.

I don't know what is "not working" for the OP, but actually his code works
if one replaces the csv-reading with a generated list:

cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = [["column_%i" % c for c in xrange(5)] for l in xrange(7)]
for line in reader:
if cnt 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1
print p
You are right of course that it is the most unpythonic way imaginabe to do
it. But it works.

Diez
Jul 4 '06 #10

P: n/a
Roman wrote:
(please dont top-post - corrected)
>
Iain King wrote:
>>Roman wrote:
>>>I would appreciate it if somebody could tell me where I went wrong in
the following snipet:
(snip)
>>What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert
Iain


Thanks for your help

My intention is to create matrix based on parsed csv file. So, I
would like to have a list of columns (which are also lists).
csv = [
['L0C0', 'L0C1', 'L0C2'],
['L1C0', 'L1C1', 'L1C2'],
['L2C0', 'L2C1', 'L2C2'],
]

matrix = [[[] for l in range(len(csv))] for c in range(len(csv[0]))]

for numline, line in enumerate(csv):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

assert matrix == [
['L0C0', 'L1C0', 'L2C0'],
['L0C1', 'L1C1', 'L2C1'],
['L0C2', 'L1C2', 'L2C2']
]

NB : There are probably more elegant solutions.
I have made the following changes and it still doesn't work.
"doesn't work" is the worst possible description of a problem...

(snip)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 4 '06 #11

P: n/a
I am getting

TypeError: unsubscriptable object

when specifying

for line in reader[:7]:
Steven D'Aprano wrote:
On Tue, 04 Jul 2006 07:01:55 -0700, Roman wrote:
I would appreciate it if somebody could tell me where I went wrong in
the following snipet:

When I run I get no result

What do you mean? Does it print None?
cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break

That's a very unPythonic way of doing the job. The usual way of doing
this would be something like this:

for line in reader[:7]:
# no need for the "if cnt 6: break" clause now

for col in line:
p[:0].append(str(col))

p[:0] creates a new list, which has a string appended to it, and is then
thrown away. What are you trying to do?

If you are trying to insert the new entry at the beginning of the list,
you probably want this:

p.insert(0, str(col))
Jul 4 '06 #12

P: n/a
Roman wrote:
(please dont top-post - corrected)
>
Steven D'Aprano wrote:
>>On Tue, 04 Jul 2006 07:01:55 -0700, Roman wrote:

(snip)
>>
>>>cnt = 0
p=[]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break

That's a very unPythonic way of doing the job. The usual way of doing
this would be something like this:

for line in reader[:7]:
# no need for the "if cnt 6: break" clause now
I am getting

TypeError: unsubscriptable object

when specifying

for line in reader[:7]:
Should have been :

for line in list(reader)[:7]:
# code here
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 4 '06 #13

P: n/a
Thanks for spending so much time with me. I had since made the
following change.

matrix = [[[] for l in range(len(list(reader)[:10]))] for c in
range(len(list(reader)[7]))]
for numline, line in enumerate(reader):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

print matrix

I don't get mistakes anymore. However, still nothing gets printed
Bruno Desthuilliers wrote:
Roman wrote:
(please dont top-post - corrected)

Iain King wrote:
>Roman wrote:

I would appreciate it if somebody could tell me where I went wrong in
the following snipet:
(snip)
>What are you trying to do here? p[:0] returns a new list, of all the
elements in p up to element 0 (which is of course the empty list),
which is then appended to, but is not stored anywhere. If you want to
insert str(col) then use p.insert
Iain

Thanks for your help

My intention is to create matrix based on parsed csv file. So, I
would like to have a list of columns (which are also lists).

csv = [
['L0C0', 'L0C1', 'L0C2'],
['L1C0', 'L1C1', 'L1C2'],
['L2C0', 'L2C1', 'L2C2'],
]

matrix = [[[] for l in range(len(csv))] for c in range(len(csv[0]))]

for numline, line in enumerate(csv):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

assert matrix == [
['L0C0', 'L1C0', 'L2C0'],
['L0C1', 'L1C1', 'L2C1'],
['L0C2', 'L1C2', 'L2C2']
]

NB : There are probably more elegant solutions.
I have made the following changes and it still doesn't work.

"doesn't work" is the worst possible description of a problem...

(snip)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 4 '06 #14

P: n/a
Roman a écrit :

<ot>
Roman, please stop top-posting and learn to quote.
</ot>
Bruno Desthuilliers wrote:
>>Roman wrote:
(please dont top-post - corrected)
>>>
My intention is to create matrix based on parsed csv file. So, I
would like to have a list of columns (which are also lists).

csv = [
['L0C0', 'L0C1', 'L0C2'],
['L1C0', 'L1C1', 'L1C2'],
['L2C0', 'L2C1', 'L2C2'],
]

matrix = [[[] for l in range(len(csv))] for c in range(len(csv[0]))]

for numline, line in enumerate(csv):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

assert matrix == [
['L0C0', 'L1C0', 'L2C0'],
['L0C1', 'L1C1', 'L2C1'],
['L0C2', 'L1C2', 'L2C2']
]
Thanks for spending so much time with me. I had since made the
following change.

matrix = [[[] for l in range(len(list(reader)[:10]))] for c in
range(len(list(reader)[7]))]
Technically; this won't work. The first call to list(reader) will
consume reader.

It's also somewhat dumb (len(list(reader)[:10]) is always 10) and
inefficient (you're calling list(reader) twice, when you could call it
just once).

Instead of trying anything at random, read the fine manual and try to
understand the example I gave you.
for numline, line in enumerate(reader):
for numcol, col in enumerate(line):
matrix[numcol][numline] = col

print matrix

I don't get mistakes anymore. However, still nothing gets printed
If you don't print anything, nothing will be printed.
Jul 4 '06 #15

P: n/a
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
"000112" "CH130TTBO" "CH 130TT EL PLAS SEAT C/F W/C
BO" "207067" "Church Seats" 23 $29.00 7.50 "073088079954" "130TT
006" 02/23/1998
"000124" "CH130TTSS" "CH 130TT EL PLAS SEAT C/F W/C
SS" "207067" "Church Seats" 14 $29.00 6.75 "073088079985" "130TT 162"
"000176" "XPT562" "PP T562" "201681" "Price
Pfister" 0 $233.50 0.00 "" "" 01/22/1998
"000180" "XPT564" "PP T564" "201681" "Price
Pfister" 0 $0.00 0.00 "" "" 07/19/1996
"000224" "MO5270" "MO 5270*DBM*MON BIDET FCT L/HDL
CP" "204938" "Moen" 0 $0.00 8.00 "026508050286" "005270"
"000236" "MO5270P" "MO 5270P*DBM*BIDET FCT LVR/HDL
PB" "204938" "Moen" 0 $0.00 8.00 "026508050309" "05270P"
"000240" "MO5275" "MO 5275 *DBM* BIDET FCT L/HDLS
CP" "204938" "Moen" 1 $0.00 8.00 "" "" 11/20/2003
"000244" "MO5275P" "MO 5275P*DBM* MON BIDET FCT
PB" "204938" "Moen" 0 $0.00 8.00 "026508050347" "05275P" 01/04/1996
"000248" "MO5201" "MO 5201 *DBM* TRAD BIDET LVR FCT
CP" "204938" "Moen" 0 $0.00 6.70 "026508050354" "5201" 01/04/1996
"000260" "MO5201P" "MO 5201P TRAD BIDET FCT
LVR/H*DBM*B" "204938" "Moen" 0 $0.00 7.00 "026508050378" "5201P" 01/04/1996
"000264" "MO5201W" "MO 5201W**DBM**IDET FCT LVR/HDL
WH" "204938" "Moen" 0 $0.00 6.70 "026508050385" "05201W" 01/04/1996
"066916" "FB1418AB" "FB D2418AB 18 TOWEL BAR
AB" "220502" "Liberty
Hardware" 0 $18.70 1.15 "079171141898" "D2418AB" 04/14/1998
"066920" "FBD2424AB" "FB D2424AB 24 TOWEL BAR
AB" "220502" "Liberty
Hardware" 39 $20.50 1.32 "079171242427" "D2424AB"
"066956" "P7341FLC" "PP 734-1FLC*DBM* SNK FCT 1H L/SP
CP" "201681" "Price
Pfister" 0 $147.65 7.00 "038877420218" "7341FLC" 04/14/1998
"066960" "P7341FLW" "PP 734-1FLW FILT SNK FCT 1H L/SP
WH" "201681" "Price
Pfister" 0 $157.99 7.00 "038877420225" "7341FLW" 04/14/1998

Dennis Lee Bieber wrote:
On 4 Jul 2006 07:01:55 -0700, "Roman" <rg*******@hotmail.comdeclaimed
the following in comp.lang.python:
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
wl*****@ix.netcom.com wu******@bestiaria.com
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: we******@bestiaria.com)
HTTP://www.bestiaria.com/
Jul 4 '06 #16

P: n/a

Mike Kent wrote:
Roman wrote:
Thanks for your help

My intention is to create matrix based on parsed csv file. So, I would
like to have a list of columns (which are also lists).

I have made the following changes and it still doesn't work.
cnt = 0
p=[[], [], [], [], [], [], [], [], [], [], []]
reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
quotechar="'", delimiter='\t')
for line in reader:
if cnt 6:
break
j = 0
for col in line:
p[j].append(col)
j=j+1
cnt = cnt + 1

print p

p[j] does not give you a reference to an element inside p. It gives
you a new sublist containing one element from p. You then append a
column to that sublist. Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Try doing:

p[j] = p[j].append(col)
No, this doesn't work. append is an in-place operation, and you'll end
up setting p[j] to it's return, which is None.

Iain

Jul 5 '06 #17

P: n/a
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.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 5 '06 #18

P: n/a

Roman wrote:
Dennis Lee Bieber wrote:
On 4 Jul 2006 07:01:55 -0700, "Roman" <rg*******@hotmail.comdeclaimed
the following in comp.lang.python:
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
wl*****@ix.netcom.com wu******@bestiaria.com
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: we******@bestiaria.com)
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

------------------------

0024 - cup
0025 - saucer
0026 - teapot

Jul 5 '06 #19

P: n/a

Dennis Lee Bieber wrote:
On 5 Jul 2006 04:37:46 -0700, "Gerard Flanagan" <gr********@yahoo.co.uk>
declaimed the following in comp.lang.python:


You can use a class rather than have lists of lists:
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

Jul 5 '06 #20

This discussion thread is closed

Replies have been disabled for this discussion.