473,497 Members | 2,158 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List Manipulation

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
19 1970
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

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
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
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
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
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
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[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
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
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
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
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
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
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
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

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
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

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

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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
8253
by: Joseph Barron | last post by:
Here is a SIMPLE problem that I'm trying to solve. It works in Netscape 6.2, but IE6 gives ""No such interface supported." Below are page1.htm and page2.htm . In page1.htm, there are two...
6
4580
by: Steve Lambert | last post by:
Hi, I've knocked up a number of small routines to create and manipulate a linked list of any structure. If anyone could take a look at this code and give me their opinion and details of any...
77
16945
by: Ville Vainio | last post by:
I tried to clear a list today (which I do rather rarely, considering that just doing l = works most of the time) and was shocked, SHOCKED to notice that there is no clear() method. Dicts have it,...
25
2722
by: PNY | last post by:
Hi there, I am having some trouble with list manipulation and was hoping someone could help me. I have no problem reading in a text file as a list using filename.readlines(). However, I am...
2
6279
by: dave.dex | last post by:
Hi all, I've been searching the docs like mad and I'm a little new to python so apologies if this is a basic question. I would like to extract the results of the following query into a list -...
0
6993
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7197
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6881
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7375
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5456
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4584
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3088
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3078
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
287
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.