社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

将字符串转换为数组中的python

Isaac Harrison • 5 年前 • 1614 次点击  

我有一个字符串,我需要将它转换成一种可以遍历它的格式:

[["","","",""],["","2","",""],["","","",""],["2","","",""]]

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54326
 
1614 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Rafael Marques
Reply   •   1 楼
Rafael Marques    5 年前

我想最简单的方法是:

my_list = [["", "", "", ""], ["", "2", "", ""], ["", "", "", ""], ["2", "", "", ""]]
my_new_list = []

for a_list in my_list:
    my_new_list.extend(a_list)

for item in my_new_list:
    print(item)

输出为:

2






2

您可以迭代列表并使用 append 而不是使用 extend :

my_list = [["", "", "", ""], ["", "2", "", ""], ["", "", "", ""], ["2", "", "", ""]]
my_new_list = []

for a_list in my_list:
    for item in a_list:
        my_new_list.append(item)

for item in my_new_list:
    print(item)

正如扎克提到的,你可以看到更多的例子 here (How to make a flat list out of list of lists?)

FishingCode
Reply   •   2 楼
FishingCode    5 年前

我不知道你到底在问什么,但如果你想找到“2”所在的索引,你可以这样做,否则请详细说明:

storeString = [["","","",""],["","2","",""],["","","",""],["2","","",""]]

for i in storeString:
   if "2" in i:
     print(i.index("2"))
revliscano
Reply   •   3 楼
revliscano    5 年前

如果要获取该字符串中的列表,只需使用json加载其内容:

import json


list_ = json.loads('[["","","",""],["","2","",""],["","","",""],["2","","",""]]')

然后你可以迭代 list_ 随你的便