编辑列表中的整数

编辑列表中的整数

本文介绍了编辑列表中的整数 python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在写一些 Python 代码,遇到了一个小问题.

是否可以编辑列表中的值,例如向现有数字添加一个,或者我是否必须将其删除并重新添加.

例如:

X = [1, 2, 3]X[2] = X[2] + 1

是否可以将那个片段编辑成工作状态?

好吧,现在越来越烦人了......

这是我尝试使用的代码:

clickcache = []def record_user_click(index,keyword,url):如果 [index, keyword, url] 在 clickcache 中:arc = clickcache.index([index, keyword, url]) + 1点击缓存[弧] += 1别的:clickcache.append([索引, 关键字, url])clickcache.append([1])
解决方案

列表在 Python 中是可变的 - 见这里.因此,您可以添加、删除和编辑值.

因此您的代码将按原样运行.Python 中添加到现有值的快捷方式是:

>>>x = [1, 2, 3]>>>x[2] += 1>>>X[1,2,4]

Recently I have been working on some Python coding, and ran into a small problem.

Would it be possible to edit values in a list, like add one to an existing number, or do I have to remove it and re-add it.

For example:

X = [1, 2, 3]
X[2] = X[2] + 1

Is it possible to edit that piece into a working state?

EDIT:

OK this is getting annoying now......

Here is my code I am trying to use:

clickcache = []

def record_user_click(index,keyword,url):
if [index, keyword, url] in clickcache:
    arc = clickcache.index([index, keyword, url]) + 1
    clickcache[arc] += 1
else:
    clickcache.append([index, keyword, url])
    clickcache.append([1])
解决方案

Lists are mutable in Python - See here. So you can add, remove, and edit values in place.

So your code would work as is. The shortcut in Python for adding to existing values is:

>>> x = [1, 2, 3]
>>> x[2] += 1
>>> x
[1,2,4]

这篇关于编辑列表中的整数 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:32