len() i understood. " ".join(cities) --this is something new for me.

So iTried this :
>>> cities = [ entry[1] for entry in elements ]
>>> " ".join(cities)
'Acatari Acis Adamclisi'

Then as matrix is a list of lists i thought i could do this

dist = [ entry[2] for entry in elements ]
>>> print dist
[0.0, 183.198428622, 372.526412318]

But when trying to do the same as for cities i got this
Traceback (most recent call last):

File "<pyshell#33>", line 1, in <module>
    " ".join(dist)
TypeError: sequence item 0: expected string, float found

How can this be solved?

As I would like to have something like this.

'Acatari Acis Adamclisi'
0.0 183.198428622 372.526412318

But still i would need a column for the left side from the names of the cities.

len() i understood. " ".join(cities) --this is something new for me.

So iTried this :
>>> cities = [ entry[1] for entry in elements ]
>>> " ".join(cities)
'Acatari Acis Adamclisi'

Then as matrix is a list of lists i thought i could do this

dist = [ entry[2] for entry in elements ]
>>> print dist
[0.0, 183.198428622, 372.526412318]

But when trying to do the same as for cities i got this
Traceback (most recent call last):

File "<pyshell#33>", line 1, in <module>
    " ".join(dist)
TypeError: sequence item 0: expected string, float found

How can this be solved?

As I would like to have something like this.

'Acatari Acis Adamclisi'
0.0 183.198428622 372.526412318

But still i would need a column for the left side from the names of the cities.

You can only join strings, not floating points numbers, unless you convert them to string with str() or another function. I give you a function for that

def ntostr(number, precision=3):
    """convert a number to str with a given precision"""
    return "{0:.{1}f}".format(number, precision)

You can now use

sdist = [ ntostr(entry[2], 3) for entry in elements ]
print "XXX".join(sdist)

To add a first column, you could insert a blank string in the city list. Only you must still handle the issue of the columns widths.

You can only join strings, not floating points numbers, unless you convert them to string with str() or another function. I give you a function for that

def ntostr(number, precision=3):
    """convert a number to str with a given precision"""
    return "{0:.{1}f}".format(number, precision)

You can now use

sdist = [ ntostr(entry[2], 3) for entry in elements ]
print "XXX".join(sdist)

To add a first column, you could insert a blank string in the city list. Only you must still handle the issue of the columns widths.

It worked for the distances

elements=[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]
def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, precision)
sdist = [ ntostr(entry[2], 3) for entry in elements ]
cities = [ entry[1] for entry in elements ]
print " ".join(cities)
print " ".join(sdist)

giving the wanted result

Acatari Acis Adamclisi
0.000 183.198 372.526

but when i try to add this code to rest of the code

def line_to_entry(line):
    a, b, dist = line.split(', ')
    return (a, b, float(dist))


def read_3_entries():
    result = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            if i >= 3:
                break
            entry = line_to_entry(line)
            result.append(entry)
    return result


print read_3_entries()

def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, result)
sdist = [ ntostr(entry[2], 3) for entry in result ]
cities = [ entry[1] for entry in result ]
print " ".join(cities)
print " ".join(sdist)

it says that NameError: name 'result' is not defined


In what concerns the issue of the columns widths i am still quite a novice.

It worked for the distances

elements=[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]
def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, precision)
sdist = [ ntostr(entry[2], 3) for entry in elements ]
print " ".join(sdist)

giving the wanted result

0.000 183.198 372.526

but when i try to add this code to rest of the code

def line_to_entry(line):
    a, b, dist = line.split(', ')
    return (a, b, float(dist))


def read_3_entries():
    result = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            if i >= 3:
                break
            entry = line_to_entry(line)
            result.append(entry)
    return result


print read_3_entries()

def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, result)
sdist = [ ntostr(entry[2], 3) for entry in result ]
print " ".join(sdist)

it says that NameError: name 'result' is not defined

Also i know that for cities it worked in shell but in idle i do not really know how to deal within idle

" ".join(cities)

In what concerns the issue of the columns widths i am still quite a novice.

Your are using a variable result but there is no such variable. The 'result' in read_3_entries() exists only in the function's body, not outside the function. You must use the return value

elements = read_3_entries() # capture the return value in a variable 'elements'

def ntostr(number, precision=3):
  return "{0:.{1}f}".format(number, precision) # why did you change this ?

sdist = [ ntostr(entry[2], 3) for entry in elements ] # now use 'elements'
print " ".join(sdist)

I changed by mistake number with result as the change was intended in the line after that. I had a file where i was working with elements and and one with result.

now in what concerns columns i am not very familiar with them. What should i do to insert a blank string in the city list ?

I changed by mistake number with result as the change was intended in the line after that. I had a file where i was working with elements and and one with result.

now in what concerns columns i am not very familiar with them. What should i do to insert a blank string in the city list ?

http://docs.python.org/tutorial/datastructures.html#more-on-lists

http://docs.python.org/tutorial/datastructures.html#more-on-lists

I read the tutorial and i tried this

result = read_3_entries()
result.insert(0," ")

printed

[' ', ('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]

but it gave
at the next lines of code this error
sdist = [ ntostr(entry[2], 3) for entry in result ]
IndexError: string index out of range

i can figure out what is the problem but how would it be if there was the possibility to built a function(if it is possible ) that would print as result for the rest of the matrix a list like this name,d1,d2,d3,d5----each cite fallowed by the distances till the other cities.

Acatari Acis Adamclisi
name   d1     d2   d3

I read the tutorial and i tried this

result = read_3_entries()
result.insert(0," ")

printed

[' ', ('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]

but it gave
at the next lines of code this error
sdist = [ ntostr(entry[2], 3) for entry in result ]
IndexError: string index out of range

i can figure out what is the problem but how would it be if there was the possibility to built a function(if it is possible ) that would print as result for the rest of the matrix a list like this name,d1,d2,d3,d5----each cite fallowed by the distances till the other cities.

Acatari Acis Adamclisi
name   d1     d2   d3

You must not insert an item in the entries list but in the cities or the sdist lists, before you call join on these lists. For the cities list, you must insert a blank string (which can have as many blank characters as you want), and for the sdist list, you must insert the name of the first city.
Once this is done, you only need to repeat the operation with each city after generating a list of the distances. Then we'll put all this in a function.

I tried your advice using this:

cities = []
sdist = []
cities.insert(0,'')
sdist = [ ntostr(entry[2], 3) for entry in result ]
sdist.insert(0, 'Acatari')
cities = [ entry[1] for entry in result ]
cities.insert(0,'            ')
print " ".join(cities) 
print " ".join(sdist)

and it worked

Acatari Acis Adamclisi
Acatari 0.000 183.198 372.526

.
About generating a list of distances. Could you suggest me how could i do it?

I tried your advice using this:

cities = []
sdist = []
cities.insert(0,'')
sdist = [ ntostr(entry[2], 3) for entry in result ]
sdist.insert(0, 'Acatari')
cities = [ entry[1] for entry in result ]
cities.insert(0,'            ')
print " ".join(cities) 
print " ".join(sdist)

and it worked

Acatari Acis Adamclisi
Acatari 0.000 183.198 372.526

.
About generating a list of distances. Could you suggest me how could i do it?

I suggest that you first create a list of all the entries (cityA, cityB, dist) in Te.csv for which cityA and cityB are in the list 'cities'.

I suggest that you first create a list of all the entries (cityA, cityB, dist) in Te.csv for which cityA and cityB are in the list 'cities'.

I do not really understand how to do that. My Te.csv file has tuples like this

Acatari, Acatari, 0.0
Acatari, Acis, 183.198428622

I have to convert them in a list and and to connect it with the list cities? I know that being new in python is not an escuse but i can not really figure out what i should do.

I do not really understand how to do that. My Te.csv file has tuples like this

Acatari, Acatari, 0.0
Acatari, Acis, 183.198428622

I have to convert them in a list and and to connect it with the list cities? I know that being new in python is not an escuse but i can not really figure out what i should do.

entries = read_3_entries()
cities = [ entry[1] for entry in entries ]

def useful_entries(cities):
    result = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            entry = line_to_entry(line)
            if entry[0] in cities and entry[1] in cities:
                result.append(entry)
    return result

print useful_entries(cities)

from the resulting list, you can extract the numbers that you need.

A better code for intermediate pythonistas is

def stored_entries():
    with open("Te.csv") as filein:
        for line in filein:
            yield line_to_entry(line)
    
print [ entry for entry in stored_entries() if entry[0] in cities and entry[1] in cities ]

This should be of course 40 000 km perimeter.

Do you mean that the distances are false ?

entries = read_3_entries()
cities = [ entry[1] for entry in entries ]

def useful_entries(cities):
    result = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            entry = line_to_entry(line)
            if entry[0] in cities and entry[1] in cities:
                result.append(entry)
    return result

print useful_entries(cities)

from the resulting list, you can extract the numbers that you need.

I used this code and received this:

[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318), ('Acis', 'Acatari', 183.198428622), ('Acis', 'Acis', 0.0), ('Acis', 'Adamclisi', 555.434851863), ('Adamclisi', 'Acatari', 372.526412318), ('Adamclisi', 'Acis', 555.434851863), ('Adamclisi', 'Adamclisi', 0.0)]

What the next step should be ?

I used this code and received this:

[('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318), ('Acis', 'Acatari', 183.198428622), ('Acis', 'Acis', 0.0), ('Acis', 'Adamclisi', 555.434851863), ('Adamclisi', 'Acatari', 372.526412318), ('Adamclisi', 'Acis', 555.434851863), ('Adamclisi', 'Adamclisi', 0.0)]

What the next step should be ?

Extract from this list the list of entries for which entry[0] == cities[1] and you will find your second line. Then do the same with cities[2]. You do it yourself this time.

Extract from this list the list of entries for which entry[0] == cities[1] and you will find your second line. Then do the same with cities[2]. You do it yourself this time.

i thought of something like this:
Should i use something like

result = useful_entries(cities)
if result[0] == cities[1]:
    print [entry[2] for entry in result]

but it does not show what i want
I also tried

result = useful_entries(cities)
def get_it(result):
    res = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            entry = line_to_entry(line)
            if result[0] == cities[1]:
                res.append(entry)
    return res
print get_it(result)

but it only printed []
i should definetily change it and try something else?

i thought of something like this:
Should i use something like

result = useful_entries(cities)
if result[0] == cities[1]:
    print [entry[2] for entry in result]

but it does not show what i want
I also tried

result = useful_entries(cities)
def get_it(result):
    res = list()
    with open("Te.csv") as filein:
        for i, line in enumerate(filein):
            entry = line_to_entry(line)
            if result[0] == cities[1]:
                res.append(entry)
    return res
print get_it(result)

but it only printed []
i should definetily change it and try something else?

Once you have the list that we read before, you don't need to read in the file again. We are only trying to take a sublist. The solution is in the python tutorial.

The python tutorial you send me when i was trying to insert a blank space in the list?
Even so in my current code why doesn't return something?

The python tutorial you send me when i was trying to insert a blank space in the list?
Even so in my current code why doesn't return something?

Because you're using result[0] instead of entry[0].

Because you're using result[0] instead of entry[0].

But i use result = useful_entries(cities) as the entries generated by the previos function.
And if i were not usong the curreent function could i still be using

if result[0] == cities[1]: #with entries instead of result
                res.append(entry[2])

Or i do not really understand?

But i use result = useful_entries(cities) as the entries generated by the previos function.
And if i were not usong the curreent function could i still be using

if result[0] == cities[1]: #with entries instead of result
                res.append(entry[2])

Or i do not really understand?

I don't understand. If you want to iterate over the list 'result', you can write

for entry in result:
    ...do something with the entry

You don't need to open Te.csv.

A tried this

cities = []
cities = [ entry[1] for entry in result ]

print "     ".join(cities)

for city in cities:
    sdist = []
    sdist = [ ntostr(entry[2], 3) for entry in result ]
    sdist.insert(0, city)
    print " ".join(sdist)

entries = read_3_entries()
cities = [ entry[1] for entry in entries ]

and it will print

Acatari     Acis     Adamclisi
Acatari 0.000 183.198 372.526
Acis 0.000 183.198 372.526
Adamclisi 0.000 183.198 372.526
Only the first line is ok , i mean correct, 
the next two are not in order
ast here should be like this
     Acatari     Acis     Adamclisi
Acis   183.198 0.000  372.526
Adamclisi  372.526 183.198 0.000

it seem that it doesn nu put the blank space before Acatari but between Acatari Acis Adamclisi

A tried this

cities = []
cities = [ entry[1] for entry in result ]

print "     ".join(cities)

for city in cities:
    sdist = []
    sdist = [ ntostr(entry[2], 3) for entry in result ]
    sdist.insert(0, city)
    print " ".join(sdist)

entries = read_3_entries()
cities = [ entry[1] for entry in entries ]

and it will print

Acatari     Acis     Adamclisi
Acatari 0.000 183.198 372.526
Acis 0.000 183.198 372.526
Adamclisi 0.000 183.198 372.526
Only the first line is ok , i mean correct, 
the next two are not in order
ast here should be like this
     Acatari     Acis     Adamclisi
Acis   183.198 0.000  372.526
Adamclisi  372.526 183.198 0.000

it seem that it doesn nu put the blank space before Acatari but between Acatari Acis Adamclisi

Come on, it's very simple. All you have to do is fill the missing expressions in the following code

data = [('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318), ('Acis', 'Acatari', 183.198428622), ('Acis', 'Acis', 0.0), ('Acis', 'Adamclisi', 555.434851863), ('Adamclisi', 'Acatari', 372.526412318), ('Adamclisi', 'Acis', 555.434851863), ('Adamclisi', 'Adamclisi', 0.0)]

list0 = ??? # your code here
print list0 # should print [('Acatari', 'Acatari', 0.0), ('Acatari', 'Acis', 183.198428622), ('Acatari', 'Adamclisi', 372.526412318)]

list1 = ??? # your code here
print list1 # should print [('Acis', 'Acatari', 183.198428622), ('Acis', 'Acis', 0.0), ('Acis', 'Adamclisi', 555.434851863)]

list2 = ??? # your code here
print list2 # should print [('Adamclisi', 'Acatari', 372.526412318), ('Adamclisi', 'Acis', 555.434851863), ('Adamclisi', 'Adamclisi', 0.0)]

Then it will be very easy to print the 3 lines.

But should not i use reading from a file if i want to apply to all my file?

But should not i use reading from a file if i want to apply to all my file?

First do it with 3 towns, then we'll apply the method to the whole file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.