Search code examples
pythonlistconcatenation

Error in concatenation and one more error


I'm trying to import a csv file and then output the continuous series from the file into a new csv file the contents of the file are like 1 5 6 7 8 and so on here for example the output would be ['1,1','5,5','6,8']

The error i'm getting is

>>> gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e]
TypeError: can only concatenate str (not "int") to str

Also for some reason after I do str1 = str1.replace(i, '') it turns str1 into

['2855']'2856']'3250']'3251']'3252']'3253']'3254']'3255']'3256']'3257']'3258']'3259']'3260']'3261']'3262']'3263']'3264']'3265']'3278']'3279']'3280']'3281']'3299']'3312']'3314']'3331']'3332']'3333']'3334']'3405']'3406']'3407']'3408']'3500']'4849']'4850']'5567']'5568']'5569']'6000']
2856]3250]3251]3252]3253]3254]3255]3256]3257]3258]3259]3260]3261]3262]3263]3264]3265]3278]3279]3280]3281]3299]3312]3314]3331]3332]3333]3334]3405]3406]3407]3408]3500]4849]4850]5567]5568]5569]6000]

intead of giving just

2856]3250]3251]3252]3253]3254]3255]3256]3257]3258]3259]3260]3261]3262]3263]3264]3265]3278]3279]3280]3281]3299]3312]3314]3331]3332]3333]3334]3405]3406]3407]3408]3500]4849]4850]5567]5568]5569]6000]

The code:

   with open('Book1.csv', newline='') as f:
       reader = csv.reader(f)
       data = list(reader)
       str1 = ''.join(str(e) for e in data)
       bad_chars = ["[","'"]
   for i in bad_chars :
       str1 = str1.replace(i, '')
       str1.split("]",-1)
   x = list((str1.split("]")))
   def ranges(nums):
       nums = sorted(set(nums))
       gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e]
       edges = iter(nums[:1] + sum(gaps, []) + nums[-1:])
       return list(zip(edges, edges))
   print(ranges(x)) 

Solution

  • Try this:

    def ranges(nums):
           nums = sorted(set(nums))
           gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e]
           edges = iter(nums[:1] + sum(gaps, []) + nums[-1:])
           return list(zip(edges, edges))
    
    
    data = []
    with open('Book1.csv', newline='') as f:
           reader = csv.reader(f)
           for i in reader:
               data.append(int(i[0]))
           
       
    print(ranges(data))
    

    The problem with your code was you were making the code more complex and the task redundant by joining lists of strings to a big string, and then removing the bad chars from it. Instead you could just add the integer parts of separate lists beforehand and saved the time, like I did.

    Also, the code in ranges function was giving error because you were trying to add string s to 1, which is an integer. What you didn't realise then that the x list still contained string types.