Separate the line and add to `tuple`

I know only two simple ways to split the string and add to tuple

 import re 1. tuple(map(lambda i: i, re.findall('[\d]{2}', '012345'))) # ('01', '23', '45') 2. tuple(i for i in re.findall('[\d]{2}', '012345')) # ('01', '23', '45') 

Are there other simple ways?

+4
source share
3 answers

I will go for

 s = "012345" [s[i:i + 2] for i in range(0, len(s), 2)] 

or

 tuple(s[i:i + 2] for i in range(0, len(s), 2)) 

if you really want a tuple.

+5
source

Tuples are usually used when sizes / lengths are fixed (possibly by different types) and are listed if there is an arbitrary number of values ​​of the same type.

What is the reason for using tuple instead of list here?

Samples for tuples:

  • in a fixed space (e.g. 2d: (x, y) )
  • representation of dict keys / value pairs (for example, ("John Smith", 38) )
  • things where the number of components of a tuple is known before evaluating an expression
  • ...

Samples for lists:

  • split line ( "foo|bar|buz" splits into | s: ["foo", "bar", "buz"] )
  • command line arguments ( ["-f", "/etc/fstab")
  • things in which the number of list items is (usually) unknown before evaluating the expression
  • ...
+2
source

Another alternative:

 s = '012345' map(''.join, zip(*[iter(s)]*2)) 

Or if you need a tuple:

 tuple(map(''.join, zip(*[iter(s)]*2))) 

This method of grouping elements into n-length groups comes directly from the documentation for zip() .

+1
source

Source: https://habr.com/ru/post/1396431/


All Articles