【问题标题】:Dynamically Concatenating String from a List in Python在 Python 中动态连接列表中的字符串
【发布时间】:2022-01-04 14:45:54
【问题描述】:

我想使用 python 动态连接列表中包含的字符串,但我的逻辑遇到了错误。

目标是连接字符串,直到找到以数字开头的字符串,然后将这个数字字符串隔离到它自己的变量中,然后将剩余的字符串隔离到第三个变量中。

例如:

stringList = ["One", "Two", "Three", "456", "Seven", "Eight", "Nine"]
resultOne = "OneTwoThree"
resultTwo = "456"
resultThree = "SevenEightNine"

这是我尝试过的:

stringList = ["One", "Two", "Three", "456", "Seven", "Eight", "Nine"]

i = 0

stringOne = ""
stringTwo = ""
stringThree = ""
refStart = 1

for item in stringList:
    if stringList[i].isdigit() == False:
        stringOne += stringList[i]
        i += 1
        print(stringOne)
    elif stringList[i].isdigit == True:
        stringTwo += stringList[i]
        i += 1
        print(stringTwo)
        refStart += i
    else:
        for stringList[refStart] in stringList:
            stringThree += stringList[refStart]
            refStart + 1 += i
        print(stringThree)

它会出错并显示以下消息:

File "c:\folder\Python\Scripts\test.py", line 19
    refStart + 1 += i
    ^
SyntaxError: 'operator' is an illegal expression for augmented assignment

【问题讨论】:

  • 我没有看到“refStart + 1 += i”部分代码
  • 哦,我的错。我忘了我在提交之前已经编辑过了

标签: python list concatenation


【解决方案1】:

您可以使用itertools.groupby、理解和str.join

stringList = ["One", "Two", "Three", "456", "Seven", "Eight", "Nine"]

from itertools import groupby
[''.join(g) for k,g in groupby(stringList, lambda x: x[0].isdigit())]

输出:

['OneTwoThree', '456', 'SevenEightNine']
工作原理:

groupby 会对连续的值进行分组,这里我对第一个字符进行了测试来检测它是否是数字。所以所有连续的字符串都连接在一起。

如果格式更适合您,则作为字典:

dict(enumerate(''.join(g) for k,g in groupby(stringList, 
                                             lambda x: x[0].isdigit())))

输出:

{0: 'OneTwoThree', 1: '456', 2: 'SevenEightNine'}

我不想加入连续的数字!

然后您可以将上述内容与对组标识的测试结合起来(如果字符串以数字开头,则为 True)并使用 itertools.chain 链接输出:

stringList = ["One", "Two", "Three", "456", "789", "Seven", "Eight", "Nine"]

from itertools import groupby, chain
list(chain(*(list(g) if k else [''.join(g)]
             for k,g in groupby(stringList, lambda x: x[0].isdigit()))))

输出:

['OneTwoThree', '456', '789', 'SevenEightNine']

【讨论】:

  • 这太棒了!谢谢!我试图用这个算法做的是解析一个数据库表并将输出写入 CSV。这很有帮助!
  • 虽然我还有一个问题要补充。我怎么能忽略第一个数字之后出现的任何数字?所以我有,在最后一个例子中:['OneTwoThree', '456', '789SevenEightNine']
  • @Matheus 你有重复的数字吗?或者曾经在列表中?你对真实数据提供的细节越多,就越容易给你一个好的答案;)
  • 很难说列表中有多少个,我只能确定第一次出现需要隔离。这是一个巨大的 40 万行数据集
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
相关资源
最近更新 更多