[英]How to add a tuple to the first position of a list in Python
I have a list that looks something like this 我有一个看起来像这样的清单
service = build('fusiontables', 'v1', developerKey=API_KEY)
query = "SELECT USStateCode, NOFU2008 FROM " + TABLE_ID
response = service.query().sql(sql=query).execute()
variables = {"data2008": json.encode(response['rows'])}
self.render_response('index.html', variables)
I am passing this to JavaScript and using this data to create an intensity map. 我将其传递给JavaScript,并使用此数据创建强度图。 However, the map requires the first tuple to be headers.
但是,该映射要求第一个元组为标头。 So for that I need the data to do something like this:
因此,我需要数据来执行以下操作:
var data = google.visualization.arrayToDataTable([
['State', 'No of Users'],
['US-PA', 200],
['US-CA', 300],
['US-NY', 400],
['US-TX', 500],
['US-SC', 600],
['US-MD', 700]
]);
How do I do this? 我该怎么做呢? Instead of these hardcoded values I want to use the actual data that I get from data2008.
而不是这些硬编码的值,我想使用从data2008获得的实际数据。 How do I add this to the first position?
如何将此添加到第一个位置?
To insert an object at the beginning of a list, you can use list.insert
. 要将对象插入列表的开头,可以使用
list.insert
。 The link is to the docs for mutable sequence methods, a list
being a mutable sequence (as opposed to a str
which is a sequence but not mutable) 链接指向可变序列方法的文档,
list
是可变序列(与str
相对的是序列,但不是可变序列)
data = [[u'US-AL', 290060.0], [u'US-AK', 46400.0], [u'US-AZ', 320320.0]]
data.insert(0,('State','No of users'))
您可以将其插入第一个位置:
my_list.insert(0, ('this', 'is', 'a', 'tuple'))
tuple
to the first position of a list
in Python? list
的第一个位置添加tuple
? Here's a list
: 这是一个
list
:
>>> my_list = list('abc')
>>> my_list
['a', 'b', 'c']
Insert a tuple
at the beginning (index 0): 在开始处插入一个
tuple
(索引0):
>>> my_list.insert(0, ())
>>> my_list
[(), 'a', 'b', 'c']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.