【问题标题】:split python string every nth character (string and nth character are in lists)每第 n 个字符拆分 python 字符串(字符串和第 n 个字符在列表中)
【发布时间】:2016-02-04 22:52:28
【问题描述】:

我的代码需要这样的东西: Split python string every nth character?

然而,就我而言; n 是嵌套列表中的数字,我要拆分的字符串也在嵌套列表中。

myList = [["'hello''my name'"],["'is Michael'"],["'and'", "'I like''apples'"]]

nList = [[7,9],[12],[5,8,8]

我想得到这样的东西:

myNewList = [["'hello'","'my name'"],["'is Michael'"],["'and'", "'I like'","'apples"]]

即我想按照nList中的数字对应的长度分割字符串。

我尝试使用与上面发布的链接类似的解决方案:

我的尝试:

myNewList = [myList[sum(nList[:i]):sum(nList[:i+1])] for i in range(len(nList))]

但这并不符合我的情况。

编辑:

请注意,我不想在每次引用后使用split,但是可以将其作为解决方案提供。数字各不相同,这是一个简化的场景,我用来暗示我的 XML 数据处理/写入情况。

【问题讨论】:

  • 你能解释一下nList中值的含义吗?对于给定的示例,它们是否正确?
  • 这背后的更高目的是什么?由于所有所需的短语都已由单引号分隔,因此我看不出将长度放在另一个列表中的目的。只需在原始条目上使用 split("''")
  • @Prune 当然,这是简化的场景。但是,如果您必须知道,我正在从 XML 文档中的元素中提取文本并将它们附加到嵌套列表中(每个嵌套代表每个“步骤”,或 XML 中的块)。文本必须由一定数量的字符分隔,并且这些数字是从同一个 XML 块中的另一个元素中提取的(因此这些数字也是嵌套的)。
  • @Prune 在'' 上拆分将为您提供交替的元素 ' 作为连续元素的前缀和后缀。一个正则表达式可能是一个更好的解决方案,而不是长度列表
  • 我需要澄清一下。 myList 的最后一个元素有两个元素而不是一个。然而,nList 的最后一个元素有一个简单的三个整数序列。结构不直接适用吗?

标签: python string list split numbers


【解决方案1】:

对于结构 兼容的情况,我有一个解决方案。您最初的问题的一部分是缺少下标: mlList 的每个元素都是一个包含字符串列表的子列表。我连接了最终列表并插入了 [0] 下标,现在是多余的。

距离够近,可以让你动起来吗?如果没有,我可以添加必要的 ''.join 来完成这项工作,但它比这更难看。

我也建议您使用 xml 解析工具和正则表达式。这是一个很好的练习,但它不是特别易于维护。

myList = [["'hello''my name'"], ["'is Michael'"], ["'and''I like''apples'"]]
nList = [[7, 9], [12], [5, 8, 8]]
myNewList = [[myList[phrase][0][sum(nList[phrase][:spl]):sum(nList[phrase][:spl+1])]
              for spl in range(len(nList[phrase]))]
              for phrase in range(len(myList))]

print myNewList

没关系;这是我上面尝试的一个微不足道的补充:

myList = [["'hello''my name'"], ["'is Michael'"], ["'and'", "'I like''apples'"]]
nList = [[7, 9], [12], [5, 8, 8]]
myNewList = [[''.join(myList[phrase])[sum(nList[phrase][:spl]):sum(nList[phrase][:spl+1])]
              for spl in range(len(nList[phrase]))]
              for phrase in range(len(myList))]

print myNewList

输出:

[["'hello'", "'my name'"], ["'is Michael'"], ["'and'", "'I like'", "'apples'"]]

【讨论】:

    【解决方案2】:
    res = []
    for word, nums in zip(myList, nList):
        row = []
        curr = 0
        for offset in nums:
            row.append(word[0][curr:curr+offset])
            curr += offset
        res.append(row)
    
    print(res)
    

    虽然未经测试。

    【讨论】:

      猜你喜欢
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2011-05-07
      相关资源
      最近更新 更多