Python Forum
Rearranging elements in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rearranging elements in Python
#1
i am new to Python and i cant get this.I have a List and i want to take the input from there and write those in files .

p = ['Eth1/1', 'Eth1/5','Eth2/1', 'Eth2/4','Eth101/1/1', 'Eth101/1/2', 'Eth101/1/3','Eth102/1/1', 'Eth102/1/2', 'Eth102/1/3','Eth103/1/1', 'Eth103/1/2', 'Eth103/1/3','Eth103/1/4','Eth104/1/1', 'Eth104/1/2', 'Eth104/1/3','Eth104/1/4']
What i am trying :

with open("abc1.txt", "w+") as fw1, open("abc2.txt", "w+") as fw2:
for i in p:
    if len(i.partition("/")[0]) == 4:
        fw1.write('int ' + i + '\n  mode\n')
    else:
        i = 0
        while i < len(p):
            start = p[i].split('/')
            if (start[0] == 'Eth101'):
                i += 3

            key = start[0]
            i += 1
            while i < len(p) and p[i].split('/')[0] == key:
                i += 1
            end = p[i-1].split('/')
            fw2.write('confi ' + start[0] + '/' + start[1] + '-' + end[1] + '\n mode\n')
What i am looking for :

abc1.txt should have

int Eth1/1
  mode
int Eth1/5
  mode
int Eth2/1
  mode
int Eth 2/4
  mode
abc2.txt should have :

int Eth101/1/1-3
  mode
int Eth102/1/1-3
  mode
int Eth103/1/1-4
  mode
int Eth104/1/1-4
  mode

  1. So any Eth having 1 digit before " / " ( e:g Eth1/1 or Eth2/2 )should be in one file that is abc1.txt .
  1. Any Eth having 3 digit before " / " ( e:g Eth101/1/1 or Eth 102/1/1 ) should be in another file that is abc2.txt and .As these are in ranges , need to write it like Eth101/1/1-3, Eth102/1/1-3 etc

Any Idea ?
Reply
#2
You should get an error because of line 2. The indentation is wrong.

with open("abc1.txt", "w+") as fw1, open("abc2.txt", "w+") as fw2:
    for element in p:
        if len(element.strip('Eth').split('/')[0]) == 1: # if you have one digit before the first /
            # write to abc1.txt
        else: # if you a sure that the input is correct else should work if you have three digits before /
            # write to abc2.txt
Or you can use regular expressions. I am not good at it. Never needed it so far :D
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Hey , i tried below

p = ['Eth1/1', 'Eth1/48','Eth2/1', 'Eth2/4','Eth101/1/1', 'Eth101/1/16', 'Eth101/1/3','Eth102/1/1', 'Eth102/1/2', 'Eth102/1/3','Eth103/1/1', 'Eth103/1/2', 'Eth103/1/3','Eth103/1/4','Eth104/1/1', 'Eth104/1/2', 'Eth104/1/3','Eth104/1/4']
with open("abc1.txt", "w+") as fw1, open("abc2.txt", "w+") as fw2:
    for element in p:
        if len(element.strip('Eth').split('/')[0]) == 1:    # if you have one digit before the first /
            fw1.write('int ' + i + '\n  mode\n')
           # write to abc1.txt
        else: # if you a sure that the input is correct else should work if you have three digits before /
            # write to abc2.txt   
            fw2.write('int ' + i + '\n  mode\n')
both the file abc1.txt and abc2.txt contains

int Eth104/1/4
  mode
int Eth104/1/4
  mode
int Eth104/1/4
  mode
int Eth104/1/4
  mode
Reply
#4
Are you sure that the files are not empty?
This is what I am trying - Python 3.5.2:
In [1]: cd tmp/
/home/victor/tmp

In [2]: p = ['Eth1/1', 'Eth1/5','Eth2/1', 'Eth2/4','Eth101/1/1', 'Eth101/1/2', 'Eth101/1/3','Eth102/1/1', 'Eth102/1/2', 'Eth102/1/3','Eth103/1/1', 'Eth103/1/2', 'Eth103/1/3','Eth103/1/4','Eth104/1/1', 'Eth104/1/
   ...: 2', 'Eth104/1/3','Eth104/1/4']

In [3]: with open('abc1.txt', 'w+') as fw1, open('abc2.txt', 'w+') as fw2:
   ...:     for element in p:
   ...:         if len(element.strip('Eth').split('/')[0]) == 1:
   ...:             fw1.write('int {}\n  mode\n'.format(element))
   ...:         else:
   ...:             fw2.write('int {}\n  mode\n'.format(element))
   ...:             

In [4]: 
This is what is in the files:

In [4]: cat abc1.txt
int Eth1/1
  mode
int Eth1/5
  mode
int Eth2/1
  mode
int Eth2/4
  mode

In [5]: cat abc2.txt
int Eth101/1/1
  mode
int Eth101/1/2
  mode
int Eth101/1/3
  mode
int Eth102/1/1
  mode
int Eth102/1/2
  mode
int Eth102/1/3
  mode
int Eth103/1/1
  mode
int Eth103/1/2
  mode
int Eth103/1/3
  mode
int Eth103/1/4
  mode
int Eth104/1/1
  mode
int Eth104/1/2
  mode
int Eth104/1/3
  mode
int Eth104/1/4
  mode
I don't know how you determine the ranges.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
This one i am also getting but i need to define the range in abc2.txt
101/1/1-3
102/1/1-3
103/1/1-4
104/1/1-4
Reply
#6
Any rules?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
i have a script and i think we can achieve the objective but i am missing somewhere ?

with open("abc1.txt", "w+") as fw1, open("abc2.txt", "w+") as fw2:
    for i in p:
        if len(i.partition("/")[0]) == 4:
            fw1.write('int ' + i + '\n  mode\n')
        else:
            i = 0
            while i < len(p):
                start = p[i].split('/')
                print start
                if (start[0] == 'Eth1'):
                    i += 3
                else:
                    key = start[0]
                    #print key
                    i += 1
                    while i < len(p) and p[i].split('/')[0] == key:
                        i += 1
                end = p[i-1].split('/')
                fw2.write('confi ' + start[0] + '/' + start[1] + '-' + end[1] + '\n mode\n')
            
Reply
#8
Itertools can help for this task
import io
import itertools as itt

def make_ranges(ints):
    ii = iter(sorted(ints))
    a = b = next(ii)
    for k in ii:
        if k == b + 1:
            b = k
        else:
            yield a, b
            a = b = k
    yield a, b

p = ['Eth1/1', 'Eth1/48','Eth2/1', 'Eth2/4','Eth101/1/1', 'Eth101/1/16', 'Eth101/1/3','Eth102/1/1', 'Eth102/1/2', 'Eth102/1/3','Eth103/1/1', 'Eth103/1/2', 'Eth103/1/3','Eth103/1/4','Eth104/1/1', 'Eth104/1/2', 'Eth104/1/3','Eth104/1/4']

p = [x.split('/') for x in p]
p = [(x[0],) + tuple(int(y) for y in x[1:]) for x in p]
q, r = [sorted(g) for k, g in itt.groupby(sorted(p, key=len), key=len)]

fw1 = io.StringIO()
for rec in q:
    print('/'.join(str(x) for x in rec), file=fw1)

fw2 = io.StringIO()
for k, g in itt.groupby(r, key=lambda x: x[:-1]):
    for a, b in make_ranges(int(x[-1]) for x in g):
        kk = k + (a if a == b else '{}-{}'.format(a, b),)
        print('/'.join(str(x) for x in kk), file=fw2)

print(fw1.getvalue())
print(fw2.getvalue())
Output:
Eth1/1 Eth1/48 Eth2/1 Eth2/4 Eth101/1/1 Eth101/1/3 Eth101/1/16 Eth102/1/1-3 Eth103/1/1-4 Eth104/1/1-4
Reply
#9
its saying "invalid Syntax " --
print('/'.join(str(x) for x in rec), file=fw1)
Reply
#10
Nirmal Wrote:its saying "invalid Syntax " --
When I run the exact code I posted above with python 3.5, it runs without error. I now always write python 3 code. Are you still using python 2.7? In that case, add this as the very top of your script
# -*-coding: utf8-*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to remove some elements from an array in python? gohanhango 9 980 Nov-28-2023, 08:35 AM
Last Post: Gribouillis
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,012 May-17-2022, 11:38 AM
Last Post: Larz60+
  Sorting Elements via parameters pointing to those elements. rpalmer 3 2,549 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  How does a set in python store the elements? idknuttin 5 2,700 Jul-10-2020, 10:46 PM
Last Post: Gribouillis
  How to sum up the elements of an integer using python split/join? mohanraj1986 5 3,457 Aug-27-2018, 09:13 AM
Last Post: perfringo
  Python show the combinations of list of elements zydjohn 6 7,427 Mar-06-2018, 11:23 PM
Last Post: zydjohn
  [split] Rearranging CSV columns and rows Ivan1 1 2,422 Aug-31-2017, 01:41 AM
Last Post: Ivan1

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020