【问题标题】:Convert the first string element of a list of lists to a tuple将列表列表的第一个字符串元素转换为元组
【发布时间】:2018-04-26 09:52:23
【问题描述】:
ohlc = df.values.tolist()

给我这个列表列表:

[['2018-04-09', 7044.32, 7178.11, 6661.99, 6770.73],
 ['2018-04-08', 6919.98, 7111.56, 6919.98, 7023.52],
 ['2018-04-07', 6630.51, 7050.54, 6630.51, 6911.09],
 ['2018-04-06', 6815.96, 6857.49, 6575.0, 6636.32],
 ['2018-04-05', 6848.65, 6933.82, 6644.8, 6811.47],...]

为了进一步分析,我需要将每个列表的 Datestring 转换为像 (2018,04,09) 这样的元组

谢谢

【问题讨论】:

  • 下面的答案有帮助吗?随意接受答案(左侧的绿色勾号),或要求澄清。

标签: python list data-analysis data-science nested-lists


【解决方案1】:

提示:你可以像这样用特定的分隔符分割字符串。

>>> s = '2018-04-09'
>>> s.split('-')
['2018', '04', '09']

您还可以通过类型转换将list 转换为tuple

>>> L = ["a", "b", "c"]
>>> tuple(L)
('a', 'b', 'c')

请注意,这些函数是不可变的 - 它们不会更改对象,它们会返回结果(例如,您需要使用 L = tuple(L))。

希望对您的问题有所帮助。

【讨论】:

    【解决方案2】:

    @TerryA's advice 上扩展,您可以在pandas 中进行大部分上游操作:

    lst = [['2018-04-09', 7044.32, 7178.11, 6661.99, 6770.73],
           ['2018-04-08', 6919.98, 7111.56, 6919.98, 7023.52],
           ['2018-04-07', 6630.51, 7050.54, 6630.51, 6911.09],
           ['2018-04-06', 6815.96, 6857.49, 6575.0, 6636.32],
           ['2018-04-05', 6848.65, 6933.82, 6644.8, 6811.47]]
    
    # we start with a dataframe
    df = pd.DataFrame(lst)
    
    # reassign column 0 with list comprehension + conversion to int
    df[0] = [tuple(int(i) for i in x.split('-')) for x in df[0]]
    
    # extract list
    res = df.values.tolist()
    
    [[(2018, 4, 9), 7044.32, 7178.11, 6661.99, 6770.73],
     [(2018, 4, 8), 6919.98, 7111.56, 6919.98, 7023.52],
     [(2018, 4, 7), 6630.51, 7050.54, 6630.51, 6911.09],
     [(2018, 4, 6), 6815.96, 6857.49, 6575.0, 6636.32],
     [(2018, 4, 5), 6848.65, 6933.82, 6644.8, 6811.47]]
    

    【讨论】:

      【解决方案3】:

      使用list comprehension 并就地修改列表:

      lists = [['2018-04-09', 7044.32, 7178.11, 6661.99, 6770.73],
               ['2018-04-08', 6919.98, 7111.56, 6919.98, 7023.52],
               ['2018-04-07', 6630.51, 7050.54, 6630.51, 6911.09],
               ['2018-04-06', 6815.96, 6857.49, 6575.0, 6636.32],
               ['2018-04-05', 6848.65, 6933.82, 6644.8, 6811.47]]
      
      lists[:] = [[tuple(item.split('-')) if isinstance(item, str) else item for item in sub] 
                  for sub in lists] 
      
      lists
      
      [[('2018', '04', '09'), 7044.32, 7178.11, 6661.99, 6770.73],
       [('2018', '04', '08'), 6919.98, 7111.56, 6919.98, 7023.52],
       [('2018', '04', '07'), 6630.51, 7050.54, 6630.51, 6911.09],
       [('2018', '04', '06'), 6815.96, 6857.49, 6575.0, 6636.32],
       [('2018', '04', '05'), 6848.65, 6933.82, 6644.8, 6811.47]]
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 2011-01-08
        • 2014-07-14
        相关资源
        最近更新 更多