可能重复:
将列表拆分为值上的嵌套列表
我有一个这样的列表:
['jj01','gg01',',','yy01','hh01',',','yy04','uu01']
我如何将此列表拆分为其元素 - 拆分','
如下:
[['jj01','gg01'],['yy01','hh01'],['yy04','uu01']]
提前致谢。
可能重复:
将列表拆分为值上的嵌套列表
我有一个这样的列表:
['jj01','gg01',',','yy01','hh01',',','yy04','uu01']
我如何将此列表拆分为其元素 - 拆分','
如下:
[['jj01','gg01'],['yy01','hh01'],['yy04','uu01']]
提前致谢。
一种可能的“pythonic”方式来做到这一点:
l = ['jj01','gg01',',','yy01','hh01',',','yy04','uu01']
joined = ':'.join(l)
separated = joined.split(':,:')
final = [x.split(':') for x in separated]
可以组合成一条线:
final = [x.split(':') for x in ':'.join(l).split(':,:')]
正如评论中所指出的,这个解决方案只有在列表的内容是字符串时才有效。
a = ['jj01','gg01',',','yy01','hh01',',','yy04','uu01']
b = []
d = []
for c in a:
if c == ',':
b.append(d)
d = []
else:
d.append(c)
b.append(d)
#no b contains your split data
这不是一个“聪明”的解决方案,但我认为它充其量是可读的。
人为什么这么复杂?
def process(lst):
lines = []
temp = []
for item in lst:
if item != ',':
temp.append(item)
else:
lines.append(temp)
temp = []
return lines
这是一个比我以前想出的更聪明的解决方案:
import itertools
def iter_partition(itr,sep):
iitr = iter(itr)
res = list(itertools.takewhile(lambda x: x!=sep,iitr))
while res:
yield res
res = list(itertools.takewhile(lambda x: x!=sep, iitr))
L = ['jj01','gg01',',','yy01','hh01',',','yy04','uu01']
print list(iter_partition(L,','))
但是如果你可以有连续的分隔符,这会失败: ['foo',',',',','bar']
- 你永远不会看到bar
.
还有另一个 itertools 解决方案(这个比上一个更强大):
import itertools
def iter_partition(itr,sep):
for k,v in itertools.groupby(itr,key=lambda x:x==sep):
if not k:
yield (list(v))
以下是一个更面向功能的,尽管不可读的单行解决方案。我建议采用此处发布的更具可读性的方法之一。
# where 'ls' is your list
foo = zip(*[iter(filter(lambda x: x != ',', ls))]*2)
编辑**正如@mgilson 正确指出的那样,我的解决方案假定您将始终有两个连续的项目后跟逗号。如果您的列表以一个奇怪的项目结束,它将被丢弃。
static void Main(string[] args) { List str = new List() { "jj01", "gg01", ",", "yy01", "hh01", ",", "yy04", "uu01" } ; 列表 newval = new List(); StringBuilder res = new StringBuilder(); for (int i = 0; i < str.Count; i++) { if (str[i] == ",") { res.Remove(res.Length - 3, 3); newval.Add(res.ToString()); res = new StringBuilder(); } 否则 res.Append((str[i] + " , ")); //最后一项 if (i == str.Count - 1) { res.Remove(res.Length - 3, 3); newval.Add(res. ToString()); }
}
foreach (var item in newval)
{
Console.WriteLine(item);
}
Console.ReadLine();
}