我正在做一些涉及从列表中提取数据的操作,其中每个元素都是一个字典。每个字典包含两个键值对,它们是一个字符串,然后是一个整数(即 {'ID':0, 'Zip Code':9414}),然后是一个键值对,其中键是一个字符串,然后一个列表 ({'Value':[0,0,1,1,0,1]})
我可以非常轻松地访问列表中字典中该列表中的值。但是,由于列表中有一堆元素,我必须使用 for 循环来遍历它。基本上,我的方法所做的是检查 1 是否位于列表中字典中该列表中的索引(用户指定的数字)处。如果是,它会使用来自同一字典的前两个键值对更新另一个列表。
所以,像这样:
import returnExternalList #this method returns a list generated by an external method
def checkIndex(b):
listFiltered = {}
listRaw = returnExternalList.returnList #runs the method "returnList", which will return the list
for i in listRaw:
if listRaw[i]['Value'][b] == 1:
filteredList.update({listRaw[i]['ID']: listRaw[i]['Zip Code']})
print(filteredList)
checkIndex(1)
returnExternalList.returnList:
[{'ID':1 ,'Zip Code':1 ,'Value':[0,1,0,0,1]},{'ID':2 ,'Zip Code':2 ,'Value':[0,0,0,0,0]},{'ID':3,'Zip Code':3 ,'Value':[0,1,1,1,0]},{'ID':4 ,'Zip Code':4 ,'Value':[1,0,0,0,0]}]
expected output:
[{1:1 , 3:3}]
Run Code Online (Sandbox Code Playgroud)
只需执行以下操作,我就可以非常简单地访问 for 循环外列表内的字典内列表中的值:
print(listRaw[0]['Value'][1]) would return 1, …
Run Code Online (Sandbox Code Playgroud) 例如,我有一个list = ['a', 'b', 'c']
.
我想要的是一个列表indexed(list) == [(1, 'a'), (2, 'b'), (3, 'c)]
。
是否有内置或模块?
赋值就是写一段代码,返回字符串的后半部分。得到一个错误说索引必须是整数,但我似乎无法弄清楚问题出在哪里。感谢帮助
def last_half(sent):
string_length = len(sent)
if string_length / 2 == 0:
s_half = int(string_length/2)
print(sent[s_half,-1])
elif string_length / 2 != 0:
s_half = int(round(string_length/2))
print(sent[s_half,-1])
Run Code Online (Sandbox Code Playgroud) 有一个像
a = ['string', '1', '2', 'string2', '4', 'string5', '5' ...]
Run Code Online (Sandbox Code Playgroud)
我怎样才能找到像这样的非字符串索引
[1,2,4,6 ...]
Run Code Online (Sandbox Code Playgroud)
它不起作用如果我使用
isinstance(a, str)
Run Code Online (Sandbox Code Playgroud) 这是一个与这个问题相关的元问题:如何编写无分支std :: vector扫描?.
最初提出的问题(强调我的):
我有一个
std::vector<int> data
; 我想找到小于9的所有数组索引并将它们添加到结果向量中.
然后我把它编辑成:
我有一个
std::vector<int> data
,我想找到所有小于9的元素并将它们添加到结果向量中.
然后另一位用户将其编辑为:
我有一个
std::vector<int> data
,我想找到元素小于9的所有数组索引,并将它们添加到结果向量.
我将其标记为主持人还原,说明:
我重写了这个问题(stackoverflow.com/posts/38798841/revisions),其主要目标是将"数组索引"替换为"元素",因为这实际上是被问到的 - 并且在此上下文中引用"索引/索引"会导致有些困惑.然而,用户Aconcagua推翻了我编辑的这个关键部分.我相信他的最新编辑应该回滚.
它有理由拒绝:
阿空加瓜的编辑是正确的; 用户正在收集数组指标,而不是数组元素本身
.
现在,我不太明白主持人说的是什么 - "用户正在收集阵列标记".我看到它的方式,索引是数组中元素的位置.例如,在C语言中:
char array[] = {'t', 'e', 's', 't'};
int index = 1;
char element = array[index];
printf('%c', element);
Run Code Online (Sandbox Code Playgroud)
我根本不知道他将如何或为什么收集"指数"而不是"元素".有人可以澄清一下这样我真的能理解吗?
我在python中创建了一个字符串:'HelpA'并将其标记为单词.
>>>word='HelpA'
>>>word
'HelpA' #expected string
>>>word[0:4]
'Help' #expected string
Run Code Online (Sandbox Code Playgroud)
在使用负索引调用单词时,我得到的是完整字符串而不是预期的部分字符串.
>>>word[-97:]
'HelpA' #not the expected string
Run Code Online (Sandbox Code Playgroud)
它给出了整个字符串而不是预期的字符串:'pA'
为什么会发生这种情况?
在R中我试图弄清楚如何从预定义的序列矢量中选择多个值(例如indices = c(1:3, 4:6, 10:12, ...)
).换句话说,如果我想要一个带有"indices"中第3,第5和第7个条目的新向量,我应该使用什么语法来获取只有那些序列完整的向量,例如c(10:12, ...)
?