![](/img/trans.png)
[英]I'm getting IndexError: list index out of range error in pandas when trying print a huge file
[英]why getting IndexError: string index out of range when i get no error when i print the list?
我收到 2 个函数的错误,其中 2 个函数几乎相同。 在 1 function 中,我只是打印,在另一个 function 中,我将每个单词分配给列表索引中的临时变量,而不是打印。 打印的 function 没有错误,但分配单词而不是打印的 function 给出索引超出范围错误,为什么? 请检查下面的 the_magic() 和 the_magic1() 函数:
def the_magic(str1,str2):
str1 = str1
str2 = str2
str3 = []
for n in str1.split():
for m in str2.split():
if m in n:
str3.append(n)
if(len(str3)<1):
str3 = ' '
print(str3)
for i in range(len(str3)):
print(str3[i])
return str3
print(str3[i]) gives no error but ...
def the_magic1(str1,str2):
str1 = str1
str2 = str2
str3 = []
for n in str1.split():
for m in str2.split():
if m in n:
str3.append(n)
if(len(str3)<1):
str3 = ' '
print(str3)
for i in range(len(str3)):
temp = str3[i]
if(temp == str2):
str3 = str2
else:
str3 = str3[-1]
return str3
temp = str3[i] giving error for the_magic1()
# function call :
a = "_MileyCyrus it wont let me do it twitter keeps saying over twitter capacity or something that bird keeps coming up."
b = 'it'
c = " "
b = b.split()
b = b[-1]
str4=the_magic(a,b) # no error, returns str3 and also prints each word
str4=the_magic1(a,b) #it gives error : IndexError: string index out of range
for i in list(str3):
temp = i
if(temp == str2):
str3 = str2
else:
str3 = str3[-1]
return str3
功能不一样。
# instead of printing you have:
for i in range(len(str3)):
temp = str3[i]
if(temp == str2):
str3 = str2
else:
str3 = str3[-1]
# in the second function.
# problem is, as soon as first word in str3 - which is not a string
# but this list:
# ['it', 'it', 'twitter', 'twitter', 'capacity']
# so if you loop through the words and as soon as one word
# is identical to what is given by `b` (which is `it` in this example)
# str3 (the list) gets set to "it" (str2, here b).
# and if not, str3 gets set to the last word in the list.
# in both cases str3 is not a list any more.
你应该解释你打算用它来编程什么。
str1 = str1
str2 = str2
str3 = []
在 Python 中,字符串总是被复制的,所以在处理字符串时不必担心call by reference
问题。 将其简化为:
str3 = []
for n in str1.split():
for m in str2.split():
if m in n:
str3.append(n)
显然,您正在搜索 str1 的单词中的哪些单词包含 str2 中给出的任何单词。 rest 还是看不懂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.