我有这个例子
a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission Preferred|Forbidden|Forbidden|'
b = a.split('\t')
for item in b[1].split('|'):
indeks=b[1].split('|').index(item)
print(indeks)
并且此时返回0, 1, 2, 0
这是remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission
的索引,但为什么它返回索引0而不是打印索引3?
由于
答案 0 :(得分:2)
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission Preferred|Forbidden|Forbidden|'
>>> b = a.split('\t')
>>> b
['Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission Preferred|Forbidden|Forbidden|']
>>> b[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
字符串中没有任何 \ t ,b是单项列表,其索引为零。因此,您的代码段完全错误。
据我所知,您已尝试为字符串中的竖线条分隔值派生索引。希望这段代码能够以一种非常简洁的方式完成:
>>> for i, j in enumerate(a.split('|')):
... print(i, j)
...
0 Datenfernübertragung remote data transmission
1 long-distance data transmission
2 long-distance data transfer
3 remote data transmission Preferred
4 Forbidden
5 Forbidden
6