python(2):字符串(str)与列表(list)以及数组(array)之间的转换方法

list和array的不同

在进行转换之间先研究下python中list和array(np.array)的不同:

1、list是python中内置的数据类型,其中的数据的类型可以不相同,如java中List也可以不用相同的数据,但是为了格式的统一,就要用到泛型或者ArrayList。array中的数据类型必须是一样的。
2、list中保存的数据的存放地址,而不是数据,会增加内存的占用,所以存放数据还是尽量使用array。
3、list中有append的方法,可以进行追加,而array没有追加的方法,只能通过np.append来实现追加。
4、在print的时候,打印的结果不同。list元素之间有","分割,而array之间是空格。

    list = [1,2,3,4]
    arr = np.array(list)
    print(list)
    print(arr)
out
    [1, 2, 3, 4]
    [1 2 3 4]

1.list转换为str

当list中存放的数据是整型数据或者数字的话,需要先将数据转换为字符串再进行转换:

list = [1, 2, 3, 4]
str1 = ''.join([str(x) for x in list])
str2 = ' '.join([str(x) for x in list])
str3 = '.'.join([str(x) for x in list])
print(str1)
print(str2)
print(str3)

# out
1234
1 2 3 4
1.2.3.4

2.array转换为str

list = ['a', 'b', 'c', 'd']
arr = np.array(list)
str = ''.join(arr)
print(str)

# out
abcd

3.str转换为list

在将str转化为list时,主要就是通过str的split()函数,split()参数为空时,默认以空格来做分割。直接通过list转换时是以每一个字符为分割的。

str1 = 'abcde'
str2 = 'a b c d   e'
str3 = 'a, b, c, d, e'
result1 = list(str1)
result2 = str2.split()
result3 = str3.split(', ')
print(result1)
print(result2)
print(result3)
# out
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']

4.一个综合性例子

逐行读取两个txt文件的rgb的数据。对比后8位并看其误差分布

import linecache
i_5 = 0
i_10 = 0
i_15 = 0
i_20 = 0
i_30 = 0
i_100 = 0
sum_con = 0
for i in range(1, 156):         # 1-155
    a = linecache.getline("M_155.txt", i)      # matlab结果 bgr
    b = linecache.getline("V_155.txt", i)         # verilog bgr
    a = a[16:24]      # b [0:8]  g[8:16] r[16:24]
    b = b[16:24]
    sum = 0
    a_cont = 0
    b_cont = 0
    print("This is NO %d num" %i)
    print("a_bit:", a)
    print("b_bit:", b)
    for j in range(0, 8):
        a_int = int(a[j])
        b_int = int(b[j])
        a_cont = a_cont + a_int * (2 ** (7 - j))
        b_cont = b_cont + b_int * (2 ** (7 - j))
    print("a_d:", a_cont)
    print("b_d:", b_cont)
    sum = abs(a_cont-b_cont)
    print(sum)
    print("\n")
    if sum < 5:
        i_5 = i_5 + 1
    if sum < 10:
        i_10 = i_10 + 1
    if sum < 15:
        i_15 = i_15 + 1
    if sum < 20:
        i_20 = i_20 + 1
        sum_con = sum + sum_con
    if sum < 30:
        i_30 = i_30 + 1
    if sum < 80:
        i_100 = i_100 + 1
print(sum_con)
print("There are 155 number")
print("less than 5_cont", i_5)
print("less than 10_cont", i_10)
print("less than 15_cont", i_15)
print("less than 20_cont", i_20)
print("less than 30_cont", i_30)
print("less than 100_cont", i_100)

# out
458
There are 155 number
less than 5_cont 124
less than 10_cont 144
less than 15_cont 149
less than 20_cont 154
less than 30_cont 155
less than 100_cont 155
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值