错误无法理解:var有时被视为列表,有时被视为str



这是一个非常奇怪的错误,我在Python上根本无法理解。 下面的说明详细介绍了函数应该做什么。

f 和 f2 的创建和编写运行良好。我用一个例子测试了这个函数:histo_appels(['bob','jean','bob'],['21/03','22/03','28/03])

Python给了我一条错误消息:

line

= line.split()//list 对象没有属性 'split'。

但是在我的函数中,line 应该是从 f 中提取的字符串。

这意味着在我做line = line.split()之前,行已经是一个列表。所以好吧,我尝试直接执行line.extend(line2),这一次,Python 返回一条错误消息:

line.extend(line2) AttributeError: 'str' 对象没有属性 'extend'

这意味着该行这次是一个字符串,而据说它是之前的列表......

有什么想法吗?

def histo_appels(liste_contact, liste_date):
liste = []
s = set(liste_contact)
l = list(s)
# we identify the contact that try to call me 
# set to remove doubles: ['bob','jean','bob'] becomes ['bob','jean']
chaine = str(liste_contact)
# count() can only be applied to a string
f = open(r'c:temphistorique_contact.txt','w',encoding='utf8')
for i in range(len(s)):
liste.append((l[i],chaine.count(l[i])))
f.write(f"{l[i]} tried to call you {chaine.count(l[i])} timen")
f.close()
# example : line 1 of f contains "bob tried to call you 2 time", 
# and line 2 : "jean tried to call you 1 time"
f2 = open(r'c:temphistorique_date.txt','w',encoding='utf8')
for i in s:
liste1 = []
for j in range(len(liste_contact)):
if liste_contact[j] == i:
liste1.append(liste_date[j])
f2.write(f"on the {liste1}n")
# example line 1 of f2 is "on the ['21/03','28/03']"
# and line 2 of f2 is : "on the ['22/03']
f2.close()
# then we merge each line of f with f2 in a new file f3
f = open(r'c:temphistorique_contact.txt','r',encoding='utf8')
f2 = open(r'c:temphistorique_date.txt','r',encoding='utf8')
f3 = open(r'c:temphistorique_global.txt','w',encoding='utf8')
for line in f:
for line2 in f2:
line = line.split()
# on repasse line (=str) en liste
line2 = line2.split()
line.extend(line2)
f3.write(" ".join(line))
f3.close()
f2.close()
f.close()

问题出在嵌套for循环中:

for line in f:
for line2 in f2:
line = line.split()
# on repasse line (=str) en liste
line2 = line2.split()
line.extend(line2)
f3.write(" ".join(line))

当你进入第二个for循环时,你不断地分裂line,重新分配他的价值。我不明白你想做什么,但是在正确的 for 循环中调用 pysplitline解决了这个特定问题:

for line in f:
line = line.split()
for line2 in f2:
# on repasse line (=str) en liste
line2 = line2.split()
line.extend(line2)
f3.write(" ".join(line))

最新更新