【问题标题】:Creating string based on first letters of each element of the list根据列表中每个元素的首字母创建字符串
【发布时间】:2021-12-25 11:12:21
【问题描述】:

例子:

list = [abcc, typpaw, gfssdwww]
expected result = atgbyfcpscpsadwwww

有什么想法吗?

这是我到目前为止所做的:

def lazy_scribe(sources: list):
    result: str = ''
    i = 0
    while i < len(max(sources, key=len)):
        for source in sources:
            for char in source:
                if i <= len(source):
                    result = result + source[int(i)]
                else:
                    continue
                i += 1 / (len(sources))
                break
    return result


sources = ["python", "java", "golang"]
print(lazy_scribe(sources))
print(len(sources))

结果:“pjgyaoyvlhaaononngn”。我不知道为什么有“y”而不是 t(结果字符串中有 7 个字符)

【问题讨论】:

标签: python string list for-loop


【解决方案1】:

如果我正确理解了这个问题,这应该可以工作。

list = ["abcc", "typpaw", "gfssdwww"]

max_len = len(max(list, key=len))

res = ""
char_iterator = 0

while char_iterator < max_len:
    for word in list:
        if char_iterator < len(word):
            res += word[char_iterator]
    char_iterator += 1

print(res)

【讨论】:

  • 如果我有一个结果:“pjgyaotvlhaaonng”有没有一种简单的方法可以用它的数量替换乘法字符?示例:""pjgyaotvlhaaonng" >> "pjgyaotvlh2ao2ng"
【解决方案2】:

另一种可能的解决方案如下:

l = ['abcc', 'typpaw', 'gfssdwww']
max_len = len(max(l, key=len))
padded_l = list(zip(*[e + " " * (max_len - len(e)) for e in l]))
''.join([''.join(e) for e in padded_l]).replace(' ', '')
  1. 查找列表中最长的字符串
  2. 然后用空格填充列表中的所有字符串
  3. 在结果列表中使用zip
  4. 加入元素并替换空格以获得所需的结果

【讨论】:

  • 不错的技巧(标准化所有相同长度的字符串)!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
相关资源
最近更新 更多