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

时间:2018-05-02 23:00:47

标签: python list

我确定这个问题已经被问过了(可能是用更加雄辩的方式),但是我找不到答案,所以如果这是重复的话我会道歉。

我正在尝试遍历列表并将不是数字的每个元素添加到另一个列表中。但是,每次在原始列表中遇到一个数字时,我都希望在辅助列表中创建一个新列表。例如,如果'a3buysi8byjs'是输入,则输出将是:[[a],[b,u,y,s,i],[b,y,j,s]]。

我尝试了几件事,并决定简化我的代码并从头开始,这导致了以下内容:

Option Explicit

Public Const strSA As String = "C:\Users\kentan\Desktop\Managed Fund "

Sub iris()
    Dim i As Long
    With ActiveSheet
        With .Range(.Cells(1, "A"), .Cells(.Rows.Count, "A").End(xlUp).Offset(0, 1))
            .Sort key1:=.Columns(1), order1:=xlAscending , _
                  key2:=.Columns(2), order2:=xlAscending , _
                  Header:=xlYes, MatchCase:=False, _
                  Orientation:=xlTopToBottom, SortMethod:=xlStroke
        End With

        For i = 2 To .Rows.Count
            If LCase(.Cells(i, "A").Value2) = LCase(.Cells(i - 1, "A").Value2) And _
               LCase(.Cells(i, "A").Value2) <> LCase(.Cells(i + 1, "A").Value2) Then
                newiris .Cells(i, "A").Value2, .Cells(i, "B").Value2
            End If
        Next i
    End With
End Sub

Sub newiris(nm As String, nfo As String)
    Application.DisplayAlerts = false
    With Workbooks.Add
        Do While .Worksheets.Count > 1: .Worksheets(2).Delete: Loop
        .Worksheets(1).Cells(1, "A").Resize(1, 2) = Array(nm, nfo)
        .SaveAs filename:=strSA & nm, FileFormat:=xlOpenXMLWorkbook
        .Close savechanges:=False
    End With
    Application.DisplayAlerts = true
End Sub

*我也留下了我的评论,因为这可能有助于澄清我的意图。

提前致谢!

2 个答案:

答案 0 :(得分:1)

这适用于您的字符串:

#!/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)

会打印:

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

替代使用itertools.groupby:

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

答案 1 :(得分:1)

我相信这可以帮到你找到你想要的东西:

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)

这应打印出来:[[&#39; a&#39;],[&#39; b&#39;,&#39; u&#39;,&#39; y&#39;,&# 39; s&#39;,&#39; i&#39;],&#39; b&#39;,&#39; y&#39;,&#39; j&#39;,&#39; s& #39;]]