Show More
@@ -5,7 +5,7 b' General purpose utilities.' | |||
|
5 | 5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
6 | 6 | these things are also convenient when working at the command line. |
|
7 | 7 | |
|
8 |
$Id: genutils.py 2 |
|
|
8 | $Id: genutils.py 2847 2007-10-24 15:16:24Z vivainio $""" | |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
@@ -1058,10 +1058,47 b' class SList(list):' | |||
|
1058 | 1058 | return SList([el for el in self if pred(el)]) |
|
1059 | 1059 | else: |
|
1060 | 1060 | return SList([el for el in self if not pred(el)]) |
|
1061 | def fields(self, *fields): | |
|
1062 | """ Collect whitespace-separated fields from string list | |
|
1063 | ||
|
1064 | Allows quick awk-like usage of string lists. | |
|
1065 | ||
|
1066 | Example data (in var a, created by 'a = !ls -l'):: | |
|
1067 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog | |
|
1068 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython | |
|
1069 | ||
|
1070 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] | |
|
1071 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] | |
|
1072 | (note the joining by space). | |
|
1073 | ||
|
1074 | IndexErrors are ignored. | |
|
1075 | ||
|
1076 | Without args, fields() just split()'s the strings. | |
|
1077 | """ | |
|
1078 | if len(fields) == 0: | |
|
1079 | return [el.split() for el in self] | |
|
1080 | ||
|
1081 | res = SList() | |
|
1082 | for el in [f.split() for f in self]: | |
|
1083 | lineparts = [] | |
|
1084 | ||
|
1085 | for fd in fields: | |
|
1086 | try: | |
|
1087 | lineparts.append(el[fd]) | |
|
1088 | except IndexError: | |
|
1089 | pass | |
|
1090 | if lineparts: | |
|
1091 | res.append(" ".join(lineparts)) | |
|
1092 | ||
|
1093 | return res | |
|
1094 | ||
|
1095 | ||
|
1096 | ||
|
1097 | ||
|
1061 | 1098 | |
|
1062 | 1099 | def print_slist(arg): |
|
1063 | 1100 | """ Prettier (non-repr-like) and more informative printer for SList """ |
|
1064 | print "SList (.p, .n, .l, .s, .grep() available). Value:" | |
|
1101 | print "SList (.p, .n, .l, .s, .grep(), .fields() available). Value:" | |
|
1065 | 1102 | nlprint(arg) |
|
1066 | 1103 | |
|
1067 | 1104 | print_slist = result_display.when_type(SList)(print_slist) |
General Comments 0
You need to be logged in to leave comments.
Login now