我在Python2.7中编写脚本。我有一个像g_var = '1'
l_var = '1'
print g_var, l_var # prints 1, 1, the values of the global variables
def my_func():
global g_var # the keyword global tells that we want to change the global variable g_var
g_var = '2'
l_var = '2'
print g_var, l_var # prints 2, 2, the first being the value of the global variable, the second being the local declared variable l_var.
my_func()
print g_var, l_var # prints 2, 1, again the values of both global declared variables
这样的数组,我想从每个子集的第一个元素中创建一个列表,如:
k = ((12,12.356,40.365),(458,12.2258,42.69))
虽然我遇到了错误for i in K:
l = k[i][0]
请您告诉我如何提出解决方案?
答案 0 :(得分:0)
您正尝试按k
之类的元组访问k[(12,12.356,40.365)][0]
元组项,而有序序列项应通过其位置/索引访问(例如k[0][0]
)。< / p>
使用list comprehension从每个子集的第一个元素中获取列表:
k = ((12,12.356,40.365),(458,12.2258,42.69))
result = [t[0] for t in k]
print(result)
结果:
[12, 458]