How to split a list of strings to smaller chunks of lists of strings

How to split a list of strings to smaller chunks of lists of strings

split list into multiple lists python
c# split list into chunks linq
c# split list into multiple lists by property
python split list into chunks
c# split list in half
python split list into individual elements
how to split list values in c#
python split list into sublists based on condition

The problem I am trying to solve is the following:

I have a List<string>, let's call it "initialList".

I need to interact with all the strings in that list, so I have to enumerate it. However, the problem comes that I have to take "x" elements of it every time I interact.

x is a new Random().Next(_minValue, _maxValue); so that will be random every time.

Here is a real example of what I want to do:

Suppose the list initialList contains the following elements: test, test2, test3, test4, test5, test6, test7, test8, test9, test10, test11, test12.

I want to loop through all elements and take 2-3 strings at a time and save a new string with combined ones.

So, one possible output (varies depending which values will the Random return) is:

{ "test",  "test1", "test2" }, 
{ "test3", "test4" }, 
{ "test5", "test6" }, 
{ "test7", "test8" }, 
{ "test9", "test10", "test11" }, 
{ "test12" }

What I thought of doing:

for (var i = 0; i < _users.Count; i += _random.Next(_minMentions, _maxMentions + 1))
{
    var mergedString = ?? // get the values of the next _random.Next(_minMentions, _maxMentions + 1) strings
}

I was thinking, but if I generate the random number outside the loop, then it will always be the same. I want the amount of strings to be random each time.

Also, thought of doing LINQ by selecting the elements with index, but don't know how to proceed from there.

Any help is appreciated, thanks.


I think the best solution is to use LINQ Skip to skip over the elements you have already processed and Take to extract the random number of elements.

const int _minValue = 2;
const int _maxValue = 4; // note max of random is exclusive, so this config takes 2 or 3 elements

var _random = new Random(Guid.NewGuid().GetHashCode());

List<string> initialList = new List<string>{"test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", "test12"};

var currentPosition = 0;

while (currentPosition < initialList.Count()) {
    var toTake = _random.Next(_minValue, _maxValue);
    var mergedString = string.Join(", ", initialList.Skip(currentPosition).Take(toTake)); 
    currentPosition += toTake;
}

Note that this code might result in the last mergedString only containing one element (the last one).

Working example: C# Fiddle.

How to split a list into evenly sized chunks in Python, Splitting a list into evenly sized chunks in Python is something you will have to ways you how Duration: 4:36 Posted: Dec 3, 2018 Splitting a Generic List<T> into Multiple Chunks. “Chunking” is the technique used to break large amount of work into smaller and manageable parts. Here are a few reasons I can think of why you want to chunk, especially in a batch process where you have to process large number of items: Manage/minimize peak memory requirement. During failures,


Hope this will give you an idea.

var mergedList = new List<string>();
for(int i = 0; i < initialList.Count; ){
    var n = _random.Next(2,4);
    mergedList.Add(initialList.Skip(i).Take(n).Aggregate((x,y) => x + y));
    i += n;
}

Break a list into chunks of size N in Python, Lower and Upper Bound Theory · Analysis of Loops · Solving Recurrences · Amortized List comprehension is an elegant way to break a list in one line of code. Find size of a list in Python · Python | Categorize the given list by string size Python | Combinations of elements till size N in list · Python | Sort list of lists by  At some point, you may need to break a large string down into smaller chunks, or strings. This is the opposite of concatenation which merges or combines strings into one. To do this, you use the split function. What it does is split or breakup a string and add the data to a string array using a defined separator.


You can try direct GroupBy:

  List<string> initialList = Enumerable
    .Range(1, 15)
    .Select(i => $"test{i}")
    .ToList();

  int _minMentions = 2;
  int _maxMentions = 3;

  // Random(1): to make outcome reproducible
  // In real life should be new Random();  
  Random _random = new Random(1); 

  int group = 0;
  int groupLength = 0;

  var result = initialList
    .Select((item) => {
      if (--groupLength <= 0) {
        group += 1;
        groupLength = _random.Next(_minMentions, _maxMentions + 1);
      }

      return new { item, group };
    })
    .GroupBy(item => item.group)
    .Select(chunk => chunk
       .Select(item => item.item)
       .ToList())
    .ToList();

  string test = string.Join(Environment.NewLine, result
    .Select(items => string.Join(", ", items))); 

  Console.Write(test);

Outcome:

test1, test2
test3, test4
test5, test6
test7, test8, test9
test10, test11, test12
test13, test14
test15

Python, Python - Sublist Maximum in custom sliced List · Python | Split list into lists by particular value · Python - Cumulative List Split · Python | Split flatten String List  So far, that's what I had in mind: take at maximum 1000 piece of the items, build the request, see the payload size. If it's bigger than 1M, take 500, see the size. If the payload is bigger, take the first 250 items. If the payload if smaller, take 750 items. And so on, you get the logic.


You can use the IEnumerable.Skip and Take to loop over your initial list and create blocks of the desidered size until you have elements to process.

List<string> initiallist = new List<string>
{"test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", "test12"};

// We store the results here    
List<List<string>> result = new List<List<string>>();

Random rnd = new Random();
int pos = 0;
while (pos < initiallist.Count())
{
    // Define a block size of 2/3 elements
    int block = rnd.Next(2,4);

    // Extract the block size from the previous position
    List<string> temp = initiallist.Skip(pos).Take(block).ToList();

    // Add the sublist to our results
    result.Add(temp);

    // Point to the beginning of the next block
    pos += block;

}

Lists: N-Sized Chunks, The task at hand, dividing lists into N-sized chunks is a widespread practice Examples of items are integers, floats, strings, etc. Now, let's say you need to break down the list into smaller lists, each having 5 elements each. How to use Split in Python. At some point, you may need to break a large string down into smaller chunks, or strings. This is the opposite of concatenation which merges or combines strings into one. To do this, you use the split function. What it does is split or breakup a string and add the


Here's how you can achieve it using Linq:

var initialList = new[]
{
    "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11",
    "test12"
};

var newLists = new List<IEnumerable<string>>();
var rnd = new Random();
int minMentions = 2;
int maxMentions = 3;
int c = 0;

while (c < initialList.Length)
{
    int elementsToTake = rnd.Next(minMentions, maxMentions + 1);
    newLists.Add(initialList.Skip(c).Take(elementsToTake));
    c += elementsToTake;
}

Which results in (randomly):

{ test, test2, test3 }
{ test4, test5 }
{ test6, test7, test8 }
{ test9, test10, test11 }
{ test12 }

Note that Take will only take available items, so you don't need to worry about the elementsToTake being bigger than what initialList has left.

How to use Split in Python, may need to break a large string down into smaller chunks, or strings. is split or breakup a string and add the data to a string array using a  A list is a collection of objects such as integers, floats, strings etc. Lists are mutable data structures, i.e the contents of the list can be changed without changing it’s identity. Breaking large lists into smaller chunks is a frequently used operation to make a program more efficient.


Python Split String into Specific Length Chunks, To split a string into chunks at regular intervals based on the number of characters in Basics · Strings · Lists · Dictionary · Files · Logging · sqlite3 · OpenCV · Pillow the number of characters in the chunk, use List Comprehension with the string. In that case, the last chunk contains characters of length less than the chunk  You mean like this Split an array into parts in Powershell This function split an array into desired number of chunks and the chunks are returned as a separate array.


array_chunk - Manual, 4.2.0, PHP 5, PHP 7). array_chunk — Split an array into chunks The last chunk may contain less than size elements. string(17) "Black Canyon City" [1]=​> Now if you want to multiline strings you have to use triple single/double quotes. >>> s = """. This is a multiline string, so you can write many lines""" >>> print(s) This is a multiline string, so you can write many lines. We can have two string literals side by side, and it will behave like a single string.


chunk_split - Manual, Can be used to split a string into smaller chunks which is useful for e.g. Split string into array by regular expression; wordwrap() - Wraps a string to a It is humorous but can imitate multiple deck cuts and other (imperfectly) random events. The string split () method breaks a given string around matches of the given regular expression. Following are the two variants of split () method in Java: Parameters: regex - a delimiting regular expression Limit - the result threshold Returns: An array of strings computed by splitting the given string. Throws: PatternSyntaxException - if the