【问题标题】:Getting the nth char of each string in a list of strings获取字符串列表中每个字符串的第 n 个字符
【发布时间】:2017-09-24 04:59:43
【问题描述】:

让他们我有列表['abc', 'def', 'gh'] 我需要获取一个字符串,其中包含第一个字符串的第一个字符的内容,第二个字符的第一个,依此类推。

所以结果应该是这样的:"adgbehcf" 但问题是数组中的最后一个字符串可能有两个或一个字符。

我已经尝试过嵌套 for 循环,但是没有用。

代码:

n = 3 # The encryption number    

for i in range(n):
    x = [s[i] for s in partiallyEncrypted]
    fullyEncrypted.append(x)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

使用itertools.zip_longest的版本:

from itertools import zip_longest

lst = ['abc', 'def', 'gh']
strg = ''.join(''.join(item) for item in zip_longest(*lst, fillvalue=''))
print(strg)

要了解为什么它会起作用,看看它可能会有所帮助

for tpl in zip_longest(*lst, fillvalue=''):
    print(tpl)

【讨论】:

  • 完美运行!谢谢!但我有点尴尬,我在 2.5 小时内无法解决这个问题:(
【解决方案2】:

我猜你可以使用:

from itertools import izip_longest
l = ['abc', 'def', 'gh']
print "".join(filter(None, [i for sub in izip_longest(*l) for i in sub]))
# adgbehcf

【讨论】:

    【解决方案3】:

    请不要使用这个:

    ''.join(''.join(y) for y in zip(*x)) + 
    ''.join(y[-1] for y in x if len(y) == max(len(j) for j in x))
    

    【讨论】:

      【解决方案4】:

      拥有:

      l = ['abc', 'def', 'gh']
      

      这可行:

      s = ''
      
      In [18]: for j in range(0, len(max(l, key=len))):
          ...:     for elem in l:
          ...:         if len(elem) > j:
          ...:             s += elem[j]
      
      In [28]: s
      Out[28]: 'adgbehcf'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-12
        • 1970-01-01
        • 2012-03-17
        • 2015-12-14
        • 2022-06-13
        • 1970-01-01
        • 2021-05-26
        相关资源
        最近更新 更多