Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python将CSV文件中的数组显示为以下格式_Python_List_Csv_Tuples - Fatal编程技术网

使用python将CSV文件中的数组显示为以下格式

使用python将CSV文件中的数组显示为以下格式,python,list,csv,tuples,Python,List,Csv,Tuples,我正在尝试将某些数据从CSV文件打印到python环境。我在写了这段代码后得到了这种格式的输出 X = [('1',), ('2',), ('3',), ('4',), ('5',), ('6',)] 以下两种格式的预期输出。每个都有不同的用途 (1, 2, 3, 4, 5, 6) ((1,) ,( 2 , ) , (3 , ) , (4 ,) , (5 ,), (6 ,) ) 但是我对以我提到的其他格式显示输出感兴趣。因为在ABAQUS软件工

我正在尝试将某些数据从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',)]
这里有一个方法:

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)
更新: 要转换法语编号系统中的浮点数字符串(使用逗号而不是小数点,请正确设置区域设置并使用
locale.atof
。确保
locale.setlocale(…)
调用成功,否则您可能必须在系统上安装
fr\u fr
区域设置

>>> 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)
试试这个:

# 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语句,一个通用的代码将非常有用。再次感谢:)感谢您的快速回复。请让我知道处理时,你有十进制值。在法国,我们用逗号来表示十进制或浮点数。X=[('1,2',),('2,3',),('3,4',),('4,2',),('5,3',),('6',)]。I get Value error:以10为基数的int()的文本无效:“1,2”您可以使用类似这样的内容快速回答
tuple(tuple(t中的e用float(e.replace(',','))替换t中的e)和X中的t)
。但是您应该考虑设置适当的区域设置,并使用<代码> Loal.Oto/<代码>而不是<代码>浮点<代码> Hi@ Suththa。我尝试使用您的编码将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 u'FR')。我无法以点十进制值(1.2)的形式获得所需的输出,我仍然可以将输出视为逗号十进制分隔符输出。我尝试了一些其他代码,但没有成功。请帮我一把。是的,你说得对。我错过了那个装置。
# 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, ))