从列表中的字符串中删除Python空格

时间:2017-05-08 05:19:29

标签: python input whitespace

这是我的计划:

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

以下是我运行时会发生的事情:

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

我的程序需要接受每行,2个用空格分隔的字符串,后跟(可选)数字。 我想将它们分开,没有空格,所以它会是:

['Austin', 'Houston', 400]

然后我想把它们放在一个'图表中。所以我会使用类似的东西:

flights = collections.defaultdict(dict)

感谢任何帮助!

编辑: 第一个答案是固定的!在参考我之前的问题时,我添加了此代码,这会产生错误: 现在我有了这个:

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]

当我跑步时:

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

编辑2: 我的节目:

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]

新错误:

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

4 个答案:

答案 0 :(得分:3)

这也与您之前的问题相对应。 str.split('')与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']]

基本上,你需要在访问它之前形成你的dict!

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

答案 1 :(得分:1)

使用replace()

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

如果碰巧有标签而不是空格:

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

这与您尝试获得的确切结果相符

答案 2 :(得分:1)

对于d中的每一行,使用strip('\n')删除换行符,然后使用split()将其拆分

  

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

对于你的第二个问题, for each in d:此处d是一个列表列表,因此each是一个列表,您不能使用split()因为它已经拆分了。您可以直接使用each[0]

答案 3 :(得分:1)

或者,您可以使用正则表达式来分割线条:

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

“\ s +”表示“一个或多个空白字符” 这并没有解决将(可选)数字转换为数字格式的问题,但这似乎是另一个问题