【问题标题】:To display the arrays from CSV file to the following format using python使用 python 将 CSV 文件中的数组显示为以下格式
【发布时间】:2018-12-17 02:45:39
【问题描述】:

我正在尝试将某些数据从 CSV 文件打印到 python 环境。编写此代码后,我得到了这种格式的输出。

X = [('1',), ('2',), ('3',), ('4',), ('5',), ('6',)]

以下两种格式的预期输出。每个都有不同的用途

(1,    2,    3,    4,    5,    6)

((1,)  ,( 2  , )  , (3  , )  ,  (4  ,) , (5  ,), (6 ,) )

但我有兴趣以我提到的其他格式显示输出。因为在 ABAQUS 软件工具中,它只需要我提到的那些类型的格式。提前感谢你们的时间和耐心。 >

filename='x.csv’

with open(filename) as f:

...     data=[tuple(line) for line  in  csv.reader(f)]

...

>>> print data

[('1',), ('2',), ('3',), ('4',), ('5',), ('6',)]

【问题讨论】:

    标签: python list csv tuples


    【解决方案1】:
    X = [('1',), ('2',), ('3',), ('4',), ('5',), ('6',)]
    
    tuple(int(e) for t in X for e in t)
    # (1, 2, 3, 4, 5, 6)
    
    tuple(tuple(int(e) for e in t) for t in X)
    # ((1,), (2,), (3,), (4,), (5,), (6,))
    

    更新: 要转换法语编号系统中的浮点数字符串(使用逗号而不是小数点,请正确设置区域设置并使用locale.atof。确保locale.setlocale(...) 调用成功,否则您可能必须安装@987654324 @你系统上的语言环境

    >>> locale.setlocale(locale.LC_ALL, 'fr_FR.utf-8')
    'fr_FR.utf-8'
    >>> X= [('1,2',), ('2,3',), ('3,4',), ('4,2',), ('5,3',), ('6',)]
    >>> tuple(locale.atof(e) for t in X for e in t)
    (1.2, 2.3, 3.4, 4.2, 5.3, 6.0)
    

    【讨论】:

    • 感谢您的快速回复。当你有十进制值时,请让我知道处理。在法国,我们使用逗号来表示小数或浮点数。 X= [('1,2',), ('2,3',), ('3,4',), ('4,2',), ('5,3',), (' 6',)]。我得到值错误: int() 以 10 为底的无效文字:'1,2'
    • 您可以使用类似的方法快速回答tuple(tuple(float(e.replace(',', '.')) for e in t) for t in X)。但是您应该考虑设置正确的 LOCALE 并使用 locale.atof 而不是 float
    • 嗨@Sunitha。我尝试使用您的编码从 X= [('1,2',), ('2,3',), ('3,4',), ('4,2',), ('5,3',), ('6',)]X= [('1.2',), ('2.3',), ('3.4',), (' 4.2',), ('5.3',), ('6.0',)] ** 通过导入 **'locale' 并提及这一行 (locale.setlocale(locale.LC_ALL, 'FR '))。我无法将所需的输出作为 DOT 十进制值 (1.2),我仍然可以看到 输出为逗号小数分隔符 输出。我尝试了一些其他代码,但没有成功。请帮帮我。
    • 是的,你是对的。我错过了那个安装。
    【解决方案2】:

    这是一种方法:

    X = [('1',), ('2',), ('3',), ('4',), ('5',), ('6',)]
    
    from itertools import chain
    
    res1 = tuple(map(int, chain.from_iterable(X)))
    # (1, 2, 3, 4, 5, 6)
    
    res2 = tuple((int(t[0]), ) for t in X)
    # ((1,), (2,), (3,), (4,), (5,), (6,))
    

    或者,从res1 派生res2 并避免重复的整数转换:

    res2 = tuple((i,) for i in res1)
    

    【讨论】:

      【解决方案3】:

      试试这个:

      # for the first output
      output = tuple(int(x[0]) for x in X)
      # (1, 2, 3)
      
      # for the second output
      output_2 = tuple((int(x[0]), ) for x in X)
      # ((1, ), (2, ), (3, ))
      

      【讨论】:

      • 感谢您的回复,我如何通过与您的合作来更改我的代码?因为不用两次使用 PRINT 语句,您可以使用通用代码。再次感谢你:)
      猜你喜欢
      • 1970-01-01
      • 2017-07-06
      • 2020-11-11
      • 2015-07-08
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多