简体   繁体   English

从另一个列表中的元素创建列表,同时在python中将元素划分为后续列表

[英]Creating a list from elements in another list, while dividing the elements into subsequent lists in python

I'm sure this question has been asked (probably in much more eloquent ways), but I can't find an answer, thus I apologize if this is a duplicate. 我敢肯定这个问题已经被问到了(可能以更雄辩的方式),但是我找不到答案,因此,如果这是重复的,我深表歉意。

I am trying to iterate through a list and add each element that is not a number into another list. 我试图遍历一个列表,并将不是数字的每个元素添加到另一个列表中。 However, each time a number is encountered in the original list, I want a new list to be created within the secondary list. 但是,每次在原始列表中遇到数字时,我都希望在辅助列表中创建一个新列表。 For example, if 'a3buysi8byjs' is the input, the output would be: [[a], [b,u,y,s,i], [b,y,j,s]]. 例如,如果输入“ a3buysi8byjs”,则输出为:[[a],[b,u,y,s,i],[b,y,j,s]]。

I have tried several things, and decided to simplify my code and start from scratch, which led to the following: 我尝试了几件事,并决定简化我的代码并从头开始,这导致了以下问题:

     for e in S_li: #going through initial list, all elements available
         if e.isdigit() != True: # if it is an integer, create another list within poss 
             poss.extend(e) #if it is a letter add to the same list in poss.

*I also left my comments, because maybe that will help clarify my intent. *我也发表了意见,因为这也许有助于澄清我的意图。

Thanks in advance! 提前致谢!

This would work for your string: 这将适用于您的字符串:

#!/usr/bin/env python

data = 'a3buysi8byjs'

if data[-1].isdigit():
    data += "1"

sublist = []
target = []
for i in data:
    if i.isdigit():
        target.append(sublist)
        sublist = []
    else:
        sublist.append(i)


print(target)

Would print: 将打印:

[['a'], ['b', 'u', 'y', 's', 'i'], ['b', 'y', 'j', 's']]

Alternative using itertools.groupby: 使用itertools.groupby的替代方法:

[list(k) for i, k in itertools.groupby(data, lambda x: x.isdigit()) if not i]

I believe this should get you what you are looking for: 我相信这应该为您提供所需的东西:

s =  'a3buysi8byjs5'

partial = []
final = []
for c in s:
    if c.isdigit():
        final.append(partial)
        partial = []
    else:
        partial.append(c)

if len(partial) > 0:
    final.append(partial)

print(final)

This should print out: [['a'], ['b', 'u', 'y', 's', 'i'], ['b', 'y', 'j', 's']] 这应该打印出来:[['a'],['b','u','y','s','i'],['b','y','j','s' ]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM