【问题标题】:How to add new elements each loop in a set of tuples?如何在一组元组中的每个循环中添加新元素?
【发布时间】:2023-04-03 11:56:01
【问题描述】:

我需要帮助,最好使用理解和切片将元组字符串转换为一组元组。我只是不知道如何每次都添加新元素。

输入:('test', 'sample', 'check')

预期:{('test',),('test','sample',),('test', 'sample', 'check')}

解决这个问题的最佳方法是什么?

【问题讨论】:

  • string of tuple 是什么?

标签: python set tuples list-comprehension slice


【解决方案1】:

这样的事情可能会奏效:

x = ('test', 'sample', 'check')

set_of_tuples = {x[:i+1] for i in range(len(x))}

print(set_of_tuples)

结果是:

{('test',), ('test', 'sample'), ('test', 'sample', 'check')}

【讨论】:

    【解决方案2】:

    使用集合推导:

    {s[:i+1] for i in range(len(s))}
    # {('test',), ('test', 'sample'), ('test', 'sample', 'check')}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-07
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2018-02-02
      • 2018-07-26
      • 1970-01-01
      相关资源
      最近更新 更多