如何将一个列表添加到另一个列表中,我继续遇到整个列表中for循环中第二个列表的问题。
如果aList
为[1, 2, 3, 4]
,我希望输出为1hello, 2good, 3what...
等。
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for element in aList:
for n in myList:
newList.append[element+n]
输入:
[1, 2, 3, 4]
预期产出:
['1hello', '2good', '3what', '4tree']
答案 0 :(得分:1)
var providers = from c in Repository.Query<Company>()
where !c.IsDeleted
select new { c.Description, Id = "C" + c.Id.ToString() };
或zip
aList = ['1', '2', '3']
print [element + n for element in aList for n in myList]
['1hello', '1good', '1what', '1tree', '2hello', '2good', '2what', '2tree', '3hello', '3good', '3what', '3tree']
答案 1 :(得分:1)
您想要zip
:
In [4]: function([1, 2, 3, 4])
Out[4]: ['1hello', '2good', '3what', '4tree']
输出:
myList
您还需要将传入的值强制转换为字符串,以确保可以连接到{{1}}中的字符串。
答案 2 :(得分:1)
在你的问题中,我觉得不需要添加两个for循环。一个循环本身就足够了。
让我给出两个案例,其中一个案例符合您的需要。
案例1: - 使用一个for循环
estimator.to_TPU_estimator()
这将返回aList = [1,2,3,4]
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for i in range(len(aList)):
newList.append(str(aList[i]) + myList [i] )
return newList
案例2: - 有两个for循环
1hello , 2good ...
这将返回aList = [1,2,3,4]
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for element in aList:
for i in range(len(myList )):
newList.append(str(element) + myList [i] )
return newList
我希望这会有所帮助......