简体   繁体   English

'int'对象在列表上不可迭代

[英]'int' object is not iterable on list

Given two lists, both having String elements, write a python program using python lists to create a new string as per the rule given below: 给定两个都具有String元素的列表,请按照以下规则使用python列表编写一个python程序来创建新字符串:

The first element in list1 should be merged with last element in list2, second element in list1 should be merged with second last element in list2 and so on. list1中的第一个元素应与list2中的最后一个元素合并,list1中的第二个元素应与list2中的第二个最后元素合并,以此类推。 If an element in list1/list2 is None, then the corresponding element in the other list should be kept as it is in the merged list. 如果list1 / list2中的元素为None,则另一个列表中的相应元素应保留在合并列表中。

Sample Input: 输入样例:

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']  

Expected Output: 预期产量:

“An apple a day keeps the doctor away” “一天一苹果,医生远离我”

My code: 我的代码:

 for i,j in range(n,len(list1)):
     a = 1
     j = n - a
     s = list[i]+list[j]
     resultant_data.append(s)
     a=+1 
     n+=1

    return resultant_data

#Provide different values for the variables and test your program
list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
merged_data=merge_list(list1,list2)
print(merged_data)
  Traceback (most recent call last): line 21, in <module> merged_data=merge_list(list1,list2) line 8, in merge_list for i,j in range(n,len(list1)): TypeError: 'int' object is not iterable 

list is a reserved keyword, I think this should be the correct snippet. list是一个保留关键字,我认为这应该是正确的代码段。

 for i,j in range(n,len(list1)):
     a = 1
     j = n - a
     s = list1[i]+list2[j]
     resultant_data.append(s)
     a=+1 
     n+=1

If you want to iterate on your two lists, you can use built-in functions of Python: 如果要在两个列表上进行迭代,则可以使用Python的内置函数:

words = []
for elt0, elt1 in zip(list1, reversed(list2)):
    w = elt0
    if elt1:
       w += elt1
    words.append(s)
return " ".join(words)

The or operator is good for coalescing None into an empty string. or运算符非常适合将None合并为一个空字符串。 map for applying a function to the two lists. 将功能应用于两个列表的map lambda for creating a simple function in-line, join for merging the elements separated by spaces.. lambda用于内联创建一个简单的函数, join用于合并用空格分隔的元素。

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n'] 

print(' '.join(map(lambda x, y: (x or '')+(y or ''),list1, list2[::-1])))

An apple a day keeps the doctor away

your iterating over 2 indexes, so you need 2 ranges (iterable objects). 您要遍历2个索引,因此需要2个范围(可迭代对象)。

something like: 就像是:

def merge_list(list1, list2):
    resultant_data = []
    list2.reverse()

    for i,j in zip(range(0, len(list1)), range(0, len(list2))):
        if list2[j] is not None:
            s = list1[i]+list2[j]
        else:
            s = list1[i]
        resultant_data.append(str(s))

    return ' '.join(resultant_data)

#Provide different values for the variables and test your program
list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
merged_data=merge_list(list1,list2)
print(merged_data)

See also https://discuss.codecademy.com/t/loop-two-variables-simultaneously-in-python-3/261808/7 另请参阅https://discuss.codecademy.com/t/loop-two-variables-simultaneously-in-python-3/261808/7

I also removed the computation of the index for list2, if you just reverse the list to begin with, you can just loop over it like you do with list1 我还删除了list2索引的计算,如果您只是反转列表开头,则可以像使用list1一样循环遍历它

There's still some room for improvement, eg. 还有一些改进的余地,例如。 if list1 also contains None values, you need extra checks... 如果list1还包含None值,则需要额外的检查...


Some more info after comments: in python3 the range function returns a range object instead of a list (python2)(cfr. Python 3 range Vs Python 2 range ) But when you use it for iteration this doesn't make a difference: 注释后的更多信息:在python3中,range函数返回一个range对象而不是列表(python2)(cfr。Python 3 range Vs Python 2 range )但是当您将其用于迭代时,这没有什么区别:

    Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28)
    >>> list1=['a','b']
    >>> range(0, len(list1))
    range(0, 2)
    >>> for i in range(0, len(list1)):
    ...     print(list1[i])
    ...
    a
    b

The code I entered above gave the same error TypeError: 'int' object is not iterable in python3 我在上面输入的代码给出了相同的错误TypeError: 'int' object is not iterable在python3中TypeError: 'int' object is not iterable

The problem is that you want to iterate over 2 things and only provide 1 iterable cfr. 问题是您要迭代2件事,并且只提供1个可迭代的cfr。 object not iterable on treehouse and in this case the second iterable is not provided. 在树屋上不可迭代的对象 ,在这种情况下,不提供第二个可迭代对象。

When you do not provide a second iterable , it will iterate over the only list you provide. 当您不提供第二个iterable时,它将迭代您提供的唯一列表。 So it will think (see example below) 0 is the first thing to iterate over and 1 is the second thing to iterate over, and 0 and 1 are ints and thus not iterable. 因此,它会认为(请参见下面的示例) 0是要迭代的第一件事,而1是要迭代的第二件事,而0和1是整数,因此不可迭代。

>>> for i,j in [0,1]:
...     print i
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> for i,j in [0,1],:
...     print i
...
0
  • reversed(seq) - in-built function of Python, it's return a reverse iterator. reversed(seq)-Python的内置函数,它返回一个反向迭代器。
  • strip() - in-built function of Python is used to remove all the leading and trailing spaces from a string. strip() -Python的内置函数用于从字符串中删除所有前导和尾随空格。

Ex. 例如

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']

string1 = ""
for a1,a2 in zip(list1,reversed(list2)):
    if a2 is not None:
        string1 = string1+" "+a1+a2
    else:
        string1 = string1+" "+a1

print(string1.strip())

O/P: O / P:

An apple a day keeps the doctor away

You got that error because None is not a string as it does not consist of quotation marks like this "None". 之所以收到该错误,是因为None不是字符串,因为它不包含像“ None”这样的引号。 That's why it is considered an integer. 这就是为什么它被认为是整数。 And so an integer and a string cannot be concatenated. 因此,不能将整数和字符串连接在一起。 To avoid the error you need an if condition before the concatenation which checks if that index is None or not. 为了避免错误,在连接之前需要一个if条件,该条件检查该索引是否为None。

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
j = -1
sentence = ""
for i in list1:
    if list2[j] != None:
        word = i + list2[j]
    j-=1
    sentence = sentence + word + " "
print(sentence)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM