我想使用:
拆分器拆分第一项,但拒绝第二项等等。
我有一个包含以下内容的文件:
# cat myfile
one:two
three:four
five:six:seven
eight:nine:ten
我尝试使用python是:
with open('myfile','r') as f:
for line in f:
for word in line.split():
item1=word.split(':')[0]
item2=word.split(':')[1:]
print 'Item1: '+item1+' Item2: '+str(item2)
结果是:
Item1: one Item2: ['two']
Item1: three Item2: ['four']
Item1: five Item2: ['six', 'seven']
Item1: eight Item2: ['nine', 'ten', 'eleven']
但我想要以下结果:
Item1: one Item2: two
Item1: three Item2: four
Item1: five Item2: sixseven
Item1: eight Item2: nineteneleven
答案 0 :(得分:2)
您可以拆分一次<!-- The definition of the Log4j Configuration -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
或str.replace
以移除str.translate
,您还应拆分一次并解压缩:
:
使用替换:
In [6]: word,rest = s.split(":",1)
In [7]: rest = rest.translate(None,":")
In [8]: word,rest
Out[8]: ('eight', 'nineten')
对于python 3,你需要传递一个dict来翻译:
In [9]: s = "eight:nine:ten"
In [10]: word,rest = s.split(":",1)
In [11]: rest = rest.replace(":","")
In [12]: rest
Out[12]: 'nineten'
您也不需要迭代分割线:
word, rest = s.split(":",1)
rest = rest.translate({ord(":"): ""})
print(word,rest)
输出:
with open("test.txt") as f:
for line in f:
word, rest = line.rstrip().split(":", 1)
print('Item1: {} Item2: {}'.format(word,rest.translate(None,":"))
答案 1 :(得分:1)
你在那里完全没问题,你错过的一件事就是将拆分元素连接回字符串,这是通过使用Change_weight(G)
for i=i to n
for j=1 to n
c_i=min c_ij for all j
if c_i < 0
c_ij = c_ij-c_i for all j
c_ki = c_ki+c_i for all k
来完成的,你可以将分隔符更改为join
之类的任何其他内容等
,
输出:
separator = ""
for line in f.split("\n"):
for word in line.split():
item1=word.split(':')[0]
item2=word.split(':')[1:]
print 'Item1: '+item1+' Item2: '+separator.join(item2)