简体   繁体   English

Python列表-字符串格式作为列表索引

[英]Python list - string formatting as list indices

Depending on a condition I need to get a value from one or another function. 根据条件,我需要从一个或另一个函数获取值。 I'm trying to put it inside a simple If ... Else statement. 我试图将其放在一个简单的If ... Else语句中。 I tried to use %s string formatting but it won't work. 我尝试使用%s字符串格式,但无法正常工作。 Below code, so it will become more clear what I try to do: 在下面的代码中,因此我将尝试做的事情变得更加清楚:

if condition:
    item = my_list['%s']
else:
    item = my_other_list['%s']

# now I do something with this value:
print item % 3

This way I tried to print 3rd value of one or other list if the condition was True of False. 这样,如果condition为True,则我尝试print一个或其他列表的第3个值。 This returned an error about list indices being string. 返回有关列表索引为字符串的错误。 So I tried to put it inside int() what didn't help. 所以我试图把它放在int()里面没有用。

How should I do it? 我该怎么办? The problem is I get the value later than I declare what item is. 问题是我在声明什么是item 之后才得到值。

EDIT I will add some more infos here: 编辑我将在这里添加更多信息:

I have a for loop, that goes through ~1000 elements and processes them. 我有一个for循环,它遍历了约1000个元素并对其进行处理。 If the condition is True , it calls one function or another if false. 如果conditionTrue ,则调用一个函数,如果为false则调用另一个函数。 Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements. 现在,我不想检查相同的条件1000次,因为我知道它在这段时间内不会改变,因此想检查一次并将该方法应用于所有元素。

More code: 更多代码:

if self.dlg.comboBox_3.currentIndex == 0:
    item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2)))
else:
    item = QCustomTableWidgetItem(str(round(sum(values['%s'],2))))

for row in range(len(groups)):
    group = QTableWidgetItem(str(groups[row]))
    qTable.setItem(row,0,group)            
    qTable.setItem(row,1,item % row)

This is the actual code. 这是实际的代码。 Not the '%s' and '% row'. 不是'%s'和'%row'。 I used simplified before not to distract from the actual problem, but I think it's needed. 在不分散实际问题之前,我曾使用简化的方法,但是我认为这是必需的。 I'm sorry if it wasn't a good decision. 不好意思,对不起。

You have a reasonably large misconception about how list slicing works. 您对列表切片的工作原理有相当大的误解。 It will always happen at the time you call it, so inside your if loop itself Python will be trying to slice either of the lists by the literal string "%s" , which can't possibly work. 它总是在您调用它的时候发生,因此在if循环本身内部,Python将尝试使用文字字符串"%s"来对其中的一个列表进行切片,这可能行不通。

There is no need to do this. 不需要这样做。 You can just assign the list as the output from the if statement, and then slice that directly: 您可以将列表分配为if语句的输出,然后直接对其进行切片:

if condition:
    list_to_slice = my_list
else:
    list_to_slice = my_other_list

# now I do something with this value:
print list_to_slice[3]

Short answer: 简短答案:

'%s' is a string by definition, while a list index should be an integer by definition. '%s'根据定义是一个字符串 ,而列表索引根据定义应该是一个整数

Use int(string) if you are sure the string can be an integer (if not, it will raise a ValueError ) 如果您确定字符串可以是整数,请使用int(string) (否则,将引发ValueError

A list is made up of multiple data values that are referenced by an indice. 列表由索引引用的多个数据值组成。 So if i defined my list like so : 所以,如果我这样定义我的列表:

my_list = [apples, orange, peaches]

If I want to reference something in the list I do it like this 如果我想引用列表中的内容,我会这样

print(my_list[0]) 

The expected output for this line of code would be "apples". 此代码行的预期输出为“ apples”。 To actually add something new to a list you need to use an inbuilt method of the list object, which looks something like this : 要向列表中实际添加新内容,您需要使用list对象的内置方法,如下所示:

my_list.append("foo")

The new list would then look like this 新列表将如下所示

[apples, orange, peaches, foo]

I hope this helps. 我希望这有帮助。

I'd suggest wrapping around a function like this: 我建议环绕这样的函数:

def get_item(index, list1, list2)
    if condition:
        return list1[index]
    else:
        return list2[index]

print get_item(3)

Here is a compact way to do it: 这是一种紧凑的方法:

source = my_list if condition else my_other_list
print(source[2])

This binds a variable source to either my_list or my_other_list depending on the condition. 这将根据条件将变量source绑定到my_listmy_other_list Then the 3rd element of the selected list is accessed using an integer index. 然后,使用整数索引访问所选列表的第3个元素。 This method has the advantage that source is still bound to the list should you need to access other elements in the list. 此方法的优点是,如果您需要访问列表中的其他元素,则source仍绑定到列表。

Another way, similar to yours, is to get the element directly: 与您的方法类似,另一种方法是直接获取元素:

index = 2
if condition:
    item = my_list[index]
else:
    item = my_other_list[index]
print(item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM