python用for循环怎么给给数组赋值

Python011

python用for循环怎么给给数组赋值,第1张

思路:先定义一个数组(列表类型)出来,然后直接循环即可(需要用到列表的append函数),举例代码如下:

result_t = []

for i in range(1,5):

t = i

result_t.append(t)

Python中的for循环可以遍历一个数组,下面我就给大家分享一下在Python中for循环都有哪些基本用法。

工具/材料

CMD命令行

首先我们要打开CMD命令行,在CMD中输入python命令进入到python运行环境,如下图所示

接下来我们准备一个数组,后面会用for循环输出这个数组的内容,如下图所示

然后我们写第一个for循环,注意这里用的是for和in的搭配语法,如下图所示

最后你还可以在for循环中通过索引来循环输出数组内容,如下图所示,使用索引的时候要注意len方法的使用

使用 python list即可,因为list可以加入不同的数据类型的数据。

results = list()

lines = open('cvs_file', 'r').readlines()

for line in lines:

    elements = line.strip().split(',') # supposed limiter is ','

    for e in elements:

        try:

            results.append(float(e))

        except:

            continue

# Here results will contains all splitted elements

# all elements are string read from cvs file, so you need to

# converse it with float operator. But if element is read string

# we can catch conversion exception and throw it anyway.