Group Abstract Group Abstract

Message Boards Message Boards

0
|
5.6K Views
|
4 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Compare list of elements that are offset by one?

Posted 6 years ago

I have a log file in the form of a list of lists. The list is sorted by email address. Some log entries are partial duplicates, i.e. consecutive email addresses are the same, but login duration differs.

I want to compare each element of the list with the next in sequence to see if the email addresses are the same. If so, I want to sum the login duration, so that I end up with a list of unique email addresses and the total amount of time they were logged in.

I thought I could do this by using MapThread, having two copies of the list, and using ##1 and ##2, but I am doing something wrong.

I am sure that this type of "look ahead" function must be very obvious, but I can't quite work out how to do. Could someone point me in the right direction?

Cheers Andy

POSTED BY: Andrew Burnett
4 Replies
Posted 6 years ago

Many thanks to you both. This is really helping me to understand more sophisticated ways of using Mathematica.

POSTED BY: Andrew Burnett
Posted 6 years ago

Another way

list = {{"a", 1}, {"b", 2}, {"b", 3}, {"c", 4}, {"b", 9}};
GroupBy[list, First -> Last, Total]

(* <|"a" -> 1, "b" -> 14, "c" -> 4|> *)
POSTED BY: Rohit Namjoshi
Posted 6 years ago

That’s really good, Rohit.

POSTED BY: David Keith
Posted 6 years ago

Here is one way. It recognizes adjacent entries with the same first part as needing to be combined into a single record. It does not combine non-adjacent entries.

list = {{"a", 1}, {"b", 2}, {"b", 3}, {"c", 4}, {"b", 9}};

splitList = SplitBy[list, #[[1]] &]

(* {{{"a",1}},{{"b",2},{"b",3}},{{"c",4}},{{"b",9}}} *)

{#[[1, 1]], Total[#[[All, 2]]]} & /@ splitList

(* {{"a",1},{"b",5},{"c",4},{"b",9}} *)

But if you want a total for each email that appears in the list, you can use GatherBy:

gatheredList = GatherBy[list, #[[1]] &]

(* {{{"a",1}},{{"b",2},{"b",3},{"b",9}},{{"c",4}}} *)

{#[[1, 1]], Total[#[[All, 2]]]} & /@ gatheredList

(* {{"a",1},{"b",14},{"c",4}} *)
POSTED BY: David Keith
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard