2

Here is my program:

import sys
d = sys.stdin.readlines()
print(*d)
d = [x.strip(' ') for x in d]
print(*d)

Here is what happens when I run it:

>>> import program12 
Austin Houston 400
SanFrancisco            Fresno       700
Miami          Ames 500
# EOF
Austin Houston 400
 SanFrancisco            Fresno       700
 Miami          Ames 500

Austin Houston 400
 SanFrancisco            Fresno       700
 Miami          Ames 500

My program needs to accept per line, 2 Strings separated by white-space, followed (optionally) by a number. I want to separate these with no white-space so it would be:

['Austin', 'Houston', 400]

I then want to put these in a 'graph' so I would use something like:

flights = collections.defaultdict(dict)

Any help is appreciated!

EDIT: First answer is fixed! In reference to my previous question, I have added this code, and this generates an error: Now I have this:

import sys
d = sys.stdin.readlines()
print(*d)
d = [x.split() for x in d]
print(*d)
flights = {}
for each in d:
    flights[each.split()[0]][each.split()[1]] = each.split()[2]

And when I run:

>>> import program12
Austin Houston 400
SanFrancisco            Fresno       700
Miami          Ames 500
Austin Houston 400
 SanFrancisco            Fresno       700
 Miami          Ames 500

['Austin', 'Houston', '400'] ['SanFrancisco', 'Fresno', '700'] ['Miami', 'Ames', '500']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/program12.py", line 8, in <module>
    flights[each.split()[0]][each.split()[1]] = each.split()[2]
AttributeError: 'list' object has no attribute 'split'

EDIT 2: My program:

import sys
import collections
d = sys.stdin.readlines()
d = filter(None,d.split('\n'))
flights = {each.split()[0]:{each.split()[1]:''} for each in d}
for each in d:
    sp = each.split();flights[sp[0]][sp[1]] = '' if len(sp) <= 2 else sp[2]

New Error:

>>> import program12
 Austin Houston 400
 SanFrancisco            Fresno       700
 Miami          Ames 500
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/program12.py", line 4, in <module>
    d = filter(None,d.split('\n'))
AttributeError: 'list' object has no attribute 'split'

5 Answers 5

3

this is in correspondence with reference to your previous question too. str.split(' ') is different from str.split()

>>> d1 =  [i.split(' ') for i in filter(None,d.split('\n'))]
>>> d1
[['Houston', 'Washington', '', '', '', '', '', '', '', '1000'], ['Vancouver', 'Houston', '300'], ['Dallas', 'Sacramento', '', '', '', '', '', '', '', '', '', '800'], ['Miami', '', '', '', '', '', '', '', '', '', '', 'Ames', '2000'], ['SanFrancisco', 'LosAngeles'], ['ORD', 'PVD', '1000']]

>>> d2 =  [i.split() for i in filter(None,d.split('\n'))]
>>> d2
[['Houston', 'Washington', '1000'], ['Vancouver', 'Houston', '300'], ['Dallas', 'Sacramento', '800'], ['Miami', 'Ames', '2000'], ['SanFrancisco', 'LosAngeles'], ['ORD', 'PVD', '1000']]

Basically, you need to form your dict before accessing it!

>>> d
'\nHouston Washington        1000\nVancouver Houston 300\nDallas Sacramento          800\nMiami           Ames 2000\nSanFrancisco LosAngeles\nORD PVD 1000\n'
>>> d1=filter(None,d.split('\n'))
>>> flights = {each.split()[0]:{each.split()[1]:''} for each in d1}
>>>
>>> flights
{'Houston': {'Washington': ''}, 'SanFrancisco': {'LosAngeles': ''}, 'Dallas': {'Sacramento': ''}, 'Miami': {'Ames': ''}, 'Vancouver': {'Houston': ''}, 'ORD': {'PVD': ''}}
>>> for each in d1:sp = each.split();flights[sp[0]][sp[1]] = '' if len(sp) <= 2 else sp[2]
...
>>> flights
{'Houston': {'Washington': '1000'}, 'SanFrancisco': {'LosAngeles': ''}, 'Dallas': {'Sacramento': '800'}, 'Miami': {'Ames': '2000'}, 'Vancouver': {'Houston': '300'}, 'ORD': {'PVD': '1000'}}
Sign up to request clarification or add additional context in comments.

13 Comments

Thank you! In reference to my previous question, now the second part of code you helped me with does not work. I have edited this question if you could please take a look! :)
can you share the sample input for this?
I did. I included it at the end of this question.
that is because, you have mentioned that you are using collections.defaultdict().. so there must be a dict with keys with default values before you can run the for loop
@Coder117 You are using split on a list i.e. each and split cannot be used on a list.
|
1

Use replace():

import sys
d = sys.stdin.readlines()
print(*d)
d = [x.replace(' ','') for x in d]
print(*d)

If there happen to be tabs instead of just spaces:

import sys
d = sys.stdin.readlines()
print(*d)
d = [x.replace(' ','').replace('\t', '') for x in d]
print(*d)

This matches the exact result you are trying to get

Comments

1

Try this

import sys
d = sys.stdin.readlines()
d = [i.strip() for x in d for i in x.split()]
print(*d)

if you want line by line

import sys
for d in sys.stdin.readlines():
    d = [i.strip() for i in d.split()]
    print(*d)

Comments

1

Alternatively you could use a regex to split the lines:

import sys
import re
raw_lines = sys.stdin.readlines()
data = [re.split("\s+", line) for line in d]

"\s+" means "one or more whitespace characters" This does not address the problem of converting your (optional) number to a numeric format, but this seems like another question

Comments

1

For every line in d, strip newline characters using strip('\n') and then split it using split()

d = [x.strip().split() for x in d]

For your second question, for each in d: here d is a list of lists and so each is a list and you cannot use split() on it because it is already split. You can directly use each[0].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.