遍历列表 - 制作列表

下面的代码有一个名为“list_a”的列表——它循环了 4 次。


list_a=['red','green','blue', 'yellow']


list_1=[]

for i in list_a[0]:

    list_1.append(i)

print(list_1)


list_2=[]

for i in list_a[1]:

    list_2.append(i)

print(list_2)


list_3=[]

for i in list_a[2]:

    list_3.append(i)

print(list_3)


list_4=[]

for i in list_a[3]:

    list_4.append(i)

print(list_4)

如果您要遍历“list_a”中的每个元素并将每个字母拆分为一个字符串 - 您可以按照上面的代码进行操作。但是,有没有一种方法可以编写更短的代码——而不是每次循环遍历“list_a”的元素时都编写相同的代码。


例如 - 我的尝试是:


list_a=['red','green','blue', 'yellow']


number=0

while number<len(list_a):

    list_(int(number+1))=[]

    for i in list_a[number]:

        list_(int(number+1)).append(i)

    print(list_(int(number+1))

number+=1

希望你能帮忙 - 谢谢。


炎炎设计
浏览 168回答 5
5回答

料青山看我应如是

最短代码:[[*a]&nbsp;for&nbsp;a&nbsp;in&nbsp;list_a]输出:[['r',&nbsp;'e',&nbsp;'d'],&nbsp;['g',&nbsp;'r',&nbsp;'e',&nbsp;'e',&nbsp;'n'],&nbsp;['b',&nbsp;'l',&nbsp;'u',&nbsp;'e'],&nbsp;['y',&nbsp;'e',&nbsp;'l',&nbsp;'l',&nbsp;'o',&nbsp;'w']]说明:*a称为解包,当应用于字符串时,将其解包为单个字符。[*a]意味着我们正在将它解包到一个列表中。仅适用于 Python 3。

慕标琳琳

这就是你想要的吗?list_a = ['red', 'green', 'blue', 'yellow']list_b = [[ch for ch in word] for word in list_a]print(list_b)输出:[['r', 'e', 'd'], ['g', 'r', 'e', 'e', 'n'], ['b', 'l', 'u', 'e'], ['y', 'e', 'l', 'l', 'o', 'w']]也许:list_a = ['red', 'green', 'blue', 'yellow']for word in list_a:&nbsp; &nbsp; print([ch for ch in word])结果:['r', 'e', 'd']['g', 'r', 'e', 'e', 'n']['b', 'l', 'u', 'e']['y', 'e', 'l', 'l', 'o', 'w']

冉冉说

在你的第二个代码(尝试)中你不能像你在你的代码中那样定义列表名称(Python 不能那样工作),而是你必须制作一个列表列表(嵌套列表)来解决这个问题。我附上示例代码来解决这个问题及其输出。示例代码lst=[list(i)&nbsp;for&nbsp;i&nbsp;in&nbsp;list_a]让 list_a 成为list_a=['red','green',]它的输出[['r', 'e', 'd'],['g', 'r', 'e', 'e', 'e', 'n'如您所见,它是包含每个元素的嵌套列表

肥皂起泡泡

尝试使用以下代码:list_a=['red','green','blue', 'yellow']output_lst = []for word in list_a:&nbsp; &nbsp; temp = []&nbsp; &nbsp; for char in word:&nbsp; &nbsp; &nbsp; &nbsp; temp.append(char)&nbsp; &nbsp; output_lst.append(temp)print(output_lst)&nbsp;

喵喔喔

在遍历 中的每个元素时list_a,使用列表理解将每个字母作为字符串存储在另一个列表中。我尝试了以下代码:list_a=['red','green','blue', 'yellow']list_b=[]for i in list_a:&nbsp; &nbsp; list_b.append([j for j in i])for i in list_b:&nbsp; &nbsp; print(i)这里list_b包含每个字符串的子列表list_a。每个子列表包含一个字符串的所有字符作为一个单独的字符串。这给出了以下输出:C:\User\Python>python script.py['r', 'e', 'd']['g', 'r', 'e', 'e', 'n']['b', 'l', 'u', 'e']['y', 'e', 'l', 'l', 'o', 'w']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python