4

Unpacking the resulting list of tuples into a comma-separated values.

Using FuzzyWuzzy, I am comparing 2 files and want to output the results into a 3rd file.

Building out from this SO question: Python: Keepning only the outerloop max result when comparing string similarity of two lists

The output is:

[('Item_number', ('Item number', 91)), ('Item', ('Item name', 62))]

Using this unpack method,I was able to separate the values:

for i in mapper:
    print(*[i[0]],*[*i[1]])

Output:

Item_number Item number 91
Item Item name 62

Now, here is where I fall short. I am looking for the individual values to be comma-separated in order to be saved to a CSV file.

I tested many other solutions such as itertools but without success such as:

[('I', 't', 'e', 'm', '_', 'n', 'u', 'm', 'b', 'e', 'r', 'Item number', 91), ('I', 't', 'e', 'm', 'Item name', 62)]

Expected output:

Item_number, Item number, 91
Item, Item name, 62

Note: I am not looking for itertool specific solution but rather a solution that make sense.

Thanks for your interest.

3 Answers3

2

try unpacking it to the individual components, then printing them with commas in between:

for (i,(j,k)) in mapper:
    print(i,j,k, sep=',')

(would probably be better to give i, j, and k meaningful names, based on what the values actaully are...)

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
1

You could use a list comprehension, extending the values from the second tuples using extended iterable unpacking, and then write the list to csv (check this post on how to create a csv file from a list):

l = [('Item_number', ('Item number', 91)), ('Item', ('Item name', 62))]

[[i, *j] for i, j in l]
# [['Item_number', 'Item number', 91], ['Item', 'Item name', 62]]
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Based on your existing code, you can use such a solution:

mapper = [('Item_number', ('Item number', 91)), ('Item', ('Item name', 62))]
for i in mapper:
    print(', '.join(map(str, (*[i[0]],*[*i[1]]))))
Item_number, Item number, 91
Item, Item name, 62
LiuXiMin
  • 1,225
  • 8
  • 17
  • I learn from you the proper syntax for using ', '.join(map(str())) in that specific case. Most certainly, this will be handy moving forward. Thx – Frederic Gilbert Jun 13 '19 at 15:30