本文整理汇总了Python中list函数的典型用法代码示例。如果您正苦于以下问题:Python list函数的具体用法?Python list怎么用?Python list使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了list函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: block
def block(blockname="content"):
""" with 句で囲んだ範囲をブロックとして登録する。
既に保存されたブロックがある時、ブロックの内容を保存されたブロックで置き換えます。
保存されたブロックが無い時、ブロックの内容をそのまま出力し、ブロックを保存します。
このヘルパは通常、extends と組み合わせて使用します。
args:
blockname: ブロックの名前
"""
locals = buffer_frame_locals()
locals.setdefault("__blocks", {})
# 既に保存されたブロックがあれば、保存している内容を出力し、ここでのキャプチャ結果は破棄
if blockname in locals["__blocks"]:
buffer, locals["__buffer"] = locals["__buffer"], list()
yield
locals["__buffer"] = buffer
locals["__buffer"].append(locals["__blocks"][blockname]) # 仕様:利用後も削除せずに残しておく
# 保存されたブロックが無ければ、キャプチャ結果をブロックとして保存し、出力もする
else:
buffer, locals["__buffer"] = locals["__buffer"], list()
yield
captured = u"".join(locals["__buffer"])
locals["__buffer"] = buffer
locals["__buffer"].append(captured)
locals["__blocks"][blockname] = captured
示例2: __init__
def __init__(self, name, args=[], opts=[], **kwargs):
"""
Base class for POV objects.
@param name: POV object name
@param args: compulsory (comma separated?) pov args XX commas don't seem to matter?
@param opts: eg. CSG items
@param kwargs: key value pairs
"""
#print "Item",name,args,opts,kwargs
self.name = name
args = list(args)
for i in range(len(args)):
args[i] = map_arg(args[i])
self.args = flatten(args)
opts = list(opts)
for i in range(len(opts)):
opts[i] = map_arg(opts[i])
self.opts = flatten(opts)
self.kwargs = dict(kwargs) # take a copy
for key, val in self.kwargs.items():
if type(val) == tuple or type(val) == list:
self.kwargs[key] = map_arg(val)
示例3: jar
def jar(self):
"""Performs the 'jar' command."""
class_name = getattr(self.flags, "class")
if (class_name is None) and (len(self.args) > 0):
class_name = self.pop_args_head()
assert (class_name is not None), ("No class name specified with [--class=]<class>.")
lib_jars = []
if self.flags.jars is not None:
lib_jars.extend(self.flags.jars)
classpath = list(self.express.get_classpath(lib_jars=lib_jars))
java_opts = []
if self.flags.java_opts is not None:
java_opts = [self.flags.java_opts]
user_args = list(self.args)
logging.info("Running java class %r with parameters: %r", class_name, user_args)
cmd = [
"java",
# This property is only needed in kiji-schema v1.1 :
"-Dorg.kiji.schema.impl.AvroCellEncoder.SCHEMA_VALIDATION=DISABLED",
] + java_opts + [
"-classpath", ":".join(classpath),
class_name,
] + user_args
logging.debug("Running command:\n%s\n", " \\\n\t".join(map(repr, cmd)))
return subprocess.call(cmd)
示例4: _get_router_ids_for_agent
def _get_router_ids_for_agent(self, context, agent_db, router_ids):
result_set = set(super(L3_DVRsch_db_mixin,
self)._get_router_ids_for_agent(
context, agent_db, router_ids))
router_ids = set(router_ids or [])
if router_ids and result_set == router_ids:
# no need for extra dvr checks if requested routers are
# explicitly scheduled to the agent
return list(result_set)
# dvr routers are not explicitly scheduled to agents on hosts with
# dvr serviceable ports, so need special handling
if (self._get_agent_mode(agent_db) in
[n_const.L3_AGENT_MODE_DVR,
n_const.L3_AGENT_MODE_DVR_NO_EXTERNAL,
n_const.L3_AGENT_MODE_DVR_SNAT]):
if not router_ids:
result_set |= set(self._get_dvr_router_ids_for_host(
context, agent_db['host']))
else:
for router_id in (router_ids - result_set):
subnet_ids = self.get_subnet_ids_on_router(
context, router_id)
if (subnet_ids and
self._check_dvr_serviceable_ports_on_host(
context, agent_db['host'],
list(subnet_ids))):
result_set.add(router_id)
return list(result_set)
示例5: test_combined_non_existing_field_desc
def test_combined_non_existing_field_desc(self):
all_results = list(self.lib.items(u'id+'))
q = u'foo- id+'
results = list(self.lib.items(q))
self.assertEqual(len(all_results), len(results))
for r1, r2 in zip(all_results, results):
self.assertEqual(r1.id, r2.id)
示例6: test_invalid_final_lookup
def test_invalid_final_lookup(self):
qs = Book.objects.prefetch_related('authors__name')
with self.assertRaises(ValueError) as cm:
list(qs)
self.assertTrue('prefetch_related' in str(cm.exception))
self.assertTrue("name" in str(cm.exception))
示例7: _distance_to_W
def _distance_to_W(self, ids=None):
allneighbors = {}
weights = {}
if ids:
ids = np.array(ids)
else:
ids = np.arange(len(self._nmat))
if self.binary:
for i, neighbors in enumerate(self._nmat):
ns = [ni for ni in neighbors if ni != i]
neigh = list(ids[ns])
if len(neigh) == 0:
allneighbors[ids[i]] = []
weights[ids[i]] = []
else:
allneighbors[ids[i]] = neigh
weights[ids[i]] = [1] * len(ns)
else:
self.dmat = self.kd.sparse_distance_matrix(
self.kd, max_distance=self.threshold)
for i, neighbors in enumerate(self._nmat):
ns = [ni for ni in neighbors if ni != i]
neigh = list(ids[ns])
if len(neigh) == 0:
allneighbors[ids[i]] = []
weights[ids[i]] = []
else:
try:
allneighbors[ids[i]] = neigh
weights[ids[i]] = [self.dmat[(
i, j)] ** self.alpha for j in ns]
except ZeroDivisionError:
raise Exception, "Cannot compute inverse distance for elements at same location (distance=0)."
return allneighbors, weights
示例8: ip_addresses
def ip_addresses(conn, interface=None, include_loopback=False):
"""
Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is
ignored, unless 'include_loopback=True' is indicated. If 'interface' is
provided, then only IP addresses from that interface will be returned.
Example output looks like::
>>> ip_addresses(conn)
>>> ['192.168.1.111', '10.0.1.12']
"""
ret = set()
ifaces = linux_interfaces(conn)
if interface is None:
target_ifaces = ifaces
else:
target_ifaces = dict((k, v) for k, v in ifaces.items()
if k == interface)
if not target_ifaces:
LOG.error('Interface {0} not found.'.format(interface))
for ipv4_info in target_ifaces.values():
for ipv4 in ipv4_info.get('inet', []):
loopback = in_subnet('127.0.0.0/8', [ipv4.get('address')]) or ipv4.get('label') == 'lo'
if not loopback or include_loopback:
ret.add(ipv4['address'])
for secondary in ipv4_info.get('secondary', []):
addr = secondary.get('address')
if addr and secondary.get('type') == 'inet':
if include_loopback or (not include_loopback and not in_subnet('127.0.0.0/8', [addr])):
ret.add(addr)
if ret:
conn.logger.debug('IP addresses found: %s' % str(list(ret)))
return sorted(list(ret))
示例9: show_level
def show_level(level, path=[]):
""" Displays a level via a print statement.
Args:
level: The level to be displayed.
path: A continuous path to be displayed over the level, if provided.
"""
xs, ys = zip(*(list(level['spaces'].keys()) + list(level['walls'])))
x_lo, x_hi = min(xs), max(xs)
y_lo, y_hi = min(ys), max(ys)
path_cells = set(path)
chars = []
inverted_waypoints = {point: char for char, point in level['waypoints'].items()}
for j in range(y_lo, y_hi + 1):
for i in range(x_lo, x_hi + 1):
cell = (i, j)
if cell in path_cells:
chars.append('*')
elif cell in level['walls']:
chars.append('X')
elif cell in inverted_waypoints:
chars.append(inverted_waypoints[cell])
elif cell in level['spaces']:
chars.append(str(int(level['spaces'][cell])))
else:
chars.append(' ')
chars.append('\n')
print(''.join(chars))
示例10: dedup_value
def dedup_value(body, ctype, action="dedup_value", prop=None):
'''
Service that accepts a JSON document and enriches the prop field of that document by:
a) Removing duplicates
'''
if prop:
try:
data = json.loads(body)
except:
response.code = 500
response.add_header('content-type', 'text/plain')
return "Unable to parse body as JSON"
try:
data = json.loads(body)
except:
response.code = 500
response.add_header('content-type', 'text/plain')
return "Unable to parse body as JSON"
for p in prop.split(","):
if exists(data, p):
v = getprop(data, p)
if isinstance(v, list):
# Remove whitespace, periods, parens, brackets
clone = [re.sub("[ \.\(\)\[\]\{\}]", "", s).lower() for s in v]
# Get index of unique values
index = list(set([clone.index(s) for s in list(set(clone))]))
setprop(data, p, [v[i] for i in index])
return json.dumps(data)
示例11: test_parameter_grid
def test_parameter_grid():
"""Test basic properties of ParameterGrid."""
params1 = {"foo": [1, 2, 3]}
grid1 = ParameterGrid(params1)
assert_true(isinstance(grid1, Iterable))
assert_true(isinstance(grid1, Sized))
assert_equal(len(grid1), 3)
params2 = {"foo": [4, 2],
"bar": ["ham", "spam", "eggs"]}
grid2 = ParameterGrid(params2)
assert_equal(len(grid2), 6)
# loop to assert we can iterate over the grid multiple times
for i in xrange(2):
# tuple + chain transforms {"a": 1, "b": 2} to ("a", 1, "b", 2)
points = set(tuple(chain(*(sorted(p.items())))) for p in grid2)
assert_equal(points,
set(("bar", x, "foo", y)
for x, y in product(params2["bar"], params2["foo"])))
# Special case: empty grid (useful to get default estimator settings)
empty = ParameterGrid({})
assert_equal(len(empty), 1)
assert_equal(list(empty), [{}])
has_empty = ParameterGrid([{'C': [1, 10]}, {}])
assert_equal(len(has_empty), 3)
assert_equal(list(has_empty), [{'C': 1}, {'C': 10}, {}])
示例12: default
def default (pixels):
# Returns pixels list of tuples (R,G,B,Cluster Assignment('x' by default))
pixels = [list(x)+ list(('x',)) for x in pixels]
return pixels
示例13: parse_parameter_list
def parse_parameter_list(self, node):
parameters = []
special = []
argnames = list(node.argnames)
if node.kwargs:
special.append(make_parameter(argnames[-1], excess_keyword=1))
argnames.pop()
if node.varargs:
special.append(make_parameter(argnames[-1],
excess_positional=1))
argnames.pop()
defaults = list(node.defaults)
defaults = [None] * (len(argnames) - len(defaults)) + defaults
function_parameters = self.token_parser.function_parameters(
node.lineno)
#print >>sys.stderr, function_parameters
for argname, default in zip(argnames, defaults):
if type(argname) is tuple:
parameter = pynodes.parameter_tuple()
for tuplearg in argname:
parameter.append(make_parameter(tuplearg))
argname = normalize_parameter_name(argname)
else:
parameter = make_parameter(argname)
if default:
n_default = pynodes.parameter_default()
n_default.append(Text(function_parameters[argname]))
parameter.append(n_default)
parameters.append(parameter)
if parameters or special:
special.reverse()
parameters.extend(special)
parameter_list = pynodes.parameter_list()
parameter_list.extend(parameters)
self.function.append(parameter_list)
示例14: encode_morze
def encode_morze(text):
text_list = list()
sygnal = list()
sygnal_final = list()
morse_code = {" ":" ","A":".-","B":"-...","C":"-.-.","D":"-..","E":".","F":"..-.","G":"--.","H":"....","I":"..","J":".---","K":"-.-","L":".-..","M":"--","N":"-.","O":"---","P":".--.","Q":"--.-","R":".-.","S":"...","T":"-","U":"..-","V":"...-","W":".--","X":"-..-","Y":"-.--","Z":"--.."}
sygnal_diagram = {" ":"___", ".":"^", "-":"^^^", "*":"___"}
initial_text_list = list((str(text)).upper())
for i in initial_text_list:
if i in morse_code:
text_list.insert((len(text_list)+1),morse_code[i])
if i != ' ':
text_list.insert((len(text_list)+2),"*")
a = "".join(text_list)
a = list(a)
del a[len(a)-1]
for i in range(0,len(a)-1):
if a[i] == ' ':
del a[i-1]
for i in a:
if i in sygnal_diagram:
sygnal.insert((len(sygnal)+1),sygnal_diagram[i])
for i in range(0,len(sygnal)-1):
if sygnal[i+1] != '___' and sygnal[i] != '___':
sygnal_final.insert((len(sygnal_final)+1),sygnal[i])
sygnal_final.insert((len(sygnal_final)+1),'_')
elif sygnal[i+1] == '___' or sygnal[i] == '___':
sygnal_final.insert((len(sygnal_final)+1),sygnal[i])
elif i == len(sygnal[i])-1:
sygnal_final.insert((len(sygnal_final)+1),sygnal[i])
sygnal_final.insert((len(sygnal_final)+1),sygnal[len(sygnal)-1])
sygnal_final = "".join(sygnal_final)
return sygnal_final
示例15: _get_field_values
def _get_field_values(self):
values = {}
vocabularies_resource = get_resource_service('vocabularies')
values['anpa_category'] = vocabularies_resource.find_one(req=None, _id='categories')['items']
req = ParsedRequest()
req.where = json.dumps({'$or': [{"schema_field": "genre"}, {"_id": "genre"}]})
genre = vocabularies_resource.get(req=req, lookup=None)
if genre.count():
values['genre'] = genre[0]['items']
values['urgency'] = vocabularies_resource.find_one(req=None, _id='urgency')['items']
values['priority'] = vocabularies_resource.find_one(req=None, _id='priority')['items']
values['type'] = vocabularies_resource.find_one(req=None, _id='type')['items']
subject = vocabularies_resource.find_one(req=None, schema_field='subject')
if subject:
values['subject'] = subject['items']
else:
values['subject'] = get_subjectcodeitems()
values['desk'] = list(get_resource_service('desks').get(None, {}))
values['stage'] = self._get_stage_field_values(values['desk'])
values['sms'] = [{'qcode': 0, 'name': 'False'}, {'qcode': 1, 'name': 'True'}]
values['embargo'] = [{'qcode': 0, 'name': 'False'}, {'qcode': 1, 'name': 'True'}]
req = ParsedRequest()
req.where = json.dumps({'$or': [{"schema_field": "place"}, {"_id": "place"}, {"_id": "locators"}]})
place = vocabularies_resource.get(req=req, lookup=None)
if place.count():
values['place'] = place[0]['items']
values['ingest_provider'] = list(get_resource_service('ingest_providers').get(None, {}))
return values