简体   繁体   中英

How to reshape a list of tuples in Python?

I have a list of tuples that looks like this: B=[('dict1', 'dict2'), (1, 5), (2, 6), (3, 7), (4, 8)] . Of course dict1 and dict2 refer to two dictionaries which values are shown in the table-like view below.

I want to reshape it so that a table-like view is produced, with the purpose of later writing it to a csv file:

dict1   dict2
1       5
2       6
3       7
4       8

I have tried with data=B.reshape(2,5) but to no avail since this is not the way to reshape a list.

How could this be done in a pythonic way? Thanks!

Try

In [22]: import pandas as pd

In [23]: B=[('dict1', 'dict2'), (1, 5), (2, 6), (3, 7),]

In [24]: pd.DataFrame(B).to_csv("my_file.csv", header=False, index=False, sep="\t")

Result:

$ cat my_file.csv
  dict1 dict2
  1     5
  2     6
  3     7

If you want to write in a csv file try:

import csv
with open('file.csv', 'wb') as f:
    writer = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    writer.writerows(B)

Result:

dict1   dict2
1       5
2       6
3       7
4       8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM