Python 使用for循环创建新列表
我有一个字符串列表,希望使用for循环来更改字符串并创建一个新列表Python 使用for循环创建新列表,python,python-3.x,list,for-loop,Python,Python 3.x,List,For Loop,我有一个字符串列表,希望使用for循环来更改字符串并创建一个新列表 oldList = ['AAA','BBB','CCC'] for i in range(len(oldList)): newList = [] add1 = 'a_' add2 = '_z' newStr = add1 + oldList[i] + add2 newList.append(newStr) 列表“newList”应包含旧列表上的所有字符串以及修订内容(即[a_AA
oldList = ['AAA','BBB','CCC']
for i in range(len(oldList)):
newList = []
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
列表“newList”应包含旧列表上的所有字符串以及修订内容(即[a_AAA_z'、[a_BBB_z'、[a_CCC_z'))。但是,它只包含最后一个字符串(即,['a_CCC_z'])
我错过了什么?非常感谢。在循环之外声明输出列表。顺便说一下,它可以简化:
newList = []
for ele in oldList:
add1 = 'a_'
add2 = '_z'
newStr = add1 + ele + add2
newList.append(newStr)
或者我们可以进一步简化,如果我们使用列表理解和格式化字符串,正如@AnnZen所建议的那样
newList = [f"a_{ele}_z" for ele in oldList]
列表的声明应该在循环之外
oldList = ['AAA','BBB','CCC']
newList = []
for i in range(len(oldList)):
# should not declare newList inside for loop
#newList = []
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
print(newList)
使用列表组件:
oldList = ['AAA','BBB','CCC']
newList = ['a_' + i + '_z' for i in oldList]
您需要在for循环之外声明
newList
。如果您在for循环中声明它,那么在for循环的每次迭代中,您将重新分配变量newList
,使其等于一个空列表,因此您将丢失以前迭代中的数据(只剩下上一次迭代中的数据)
这是您的代码,声明已修复:
oldList = ['AAA','BBB','CCC']
newList = []
for i in range(len(oldList)):
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
这里有一个更简化的版本:
oldList = ['AAA','BBB','CCC']
newList = ['a_' + str + '_z' for str in oldList]
您需要在for循环外部初始化
newList
,否则它将在每次迭代时初始化。
此代码段可能会有所帮助
oldList = ['AAA','BBB','CCC']
newList = []
for i in range(len(oldList)):
add1 = 'a_'
add2 = '_z'
newStr = add1 + oldList[i] + add2
newList.append(newStr)
print(newList)
您可以使用格式化字符串和列表理解:
oldList = ['AAA','BBB','CCC']
newList = [f'a_{s}_z' for s in oldList]
print(newList)
输出:
['a_AAA_z', 'a_BBB_z', 'a_CCC_z']
将
newList=[]
放在外部,以便将新列表移到外部loop@AnnZen是的!这是一个很好的建议,我会更新我的答案。谢谢!