python2.7练习小例子(二十九)

    29):1、题目:按相反的顺序输出列表的值。

 


#!/usr/bin/python
# -*- coding: UTF-8 -*-

a = ['one', 'two', 'three']
for i in a[::-1]:
    print i

    以上实例输出结果为:

 

three
two
one

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

print '输入列表格式为:1,2,3,4'
s=input()
print type(s)
a=list(s)
print a[-1::-1]

    

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

list_ = ['a', 'b', 'c', 'd']
list_.reverse()
print( list_ )

    Python3实例,使用递归实现:

 

#!/usr/bin/env python3

a = ['one', 'two', 'three','four','five','six','seven','eight','nine','ten']

def reverse(a):
    if len(a)<=1:
        print (a[0],end=" ")
    else:
        print(a[-1],end=" ")
        reverse(a[0:-1])
        
reverse(a)

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

numlist = [100,1,23,4,5,6,6,7,7,8]
for i in range(0,len(numlist)) :
    index = len(numlist)-i-1
    print(numlist[index])

    

a = ['1','2','3']
a.sort(reverse=True)
for i in a:
    print(i)

    Python2.x 与 Python3.x均可用:

 

numbers=list(range(1,10))
reversed_list=[]
for i in range(1,10):
    reversed_list.append(numbers.pop())
print(reversed_list)

    2、题目:按逗号分隔列表。

 


#!/usr/bin/python
# -*- coding: UTF-8 -*-

L = [1,2,3,4,5]
s1 = ','.join(str(n) for n in L)
    print s1

    以上实例输出结果为:

 

1,2,3,4,5

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

L = [1, 2, 3, 4, 5]
L = repr(L)[1:-1]
print L

    

# -*- coding: UTF-8 -*-

l = [1,2,3,4,5,6,7];
k = 1;
for i in l:
    print(i,end= ('' if (k == len(l)) else ','));
    k += 1;

    

#!/usr/bin/python3

l = [1,2,3,4,5,6,7];
o = '';
for i in l:
    o += str(i)+',';
print(o[0:-1]);

    Python3 测试:

 

a=[1,2,3,4]
for i in range(0,len(a)):
    if i!=(len(a)-1):
        print(a[i],end=',')
    else:
        print(a[i])

    Python3 测试:

 

numbers=list(range(1,9))
for i in numbers:
    if(i==numbers[-1]):
        print(i)
    else:
        print(i,end=',')

    

import re

l=str(range(5));
m=re.search(r'\[(.*?)\]',l)
print( m.groups()[0] )

    这两个小例子主要练习数组的分割和反转。如果感觉不错的话,请多多点赞支持哦。。。

  原文链接:https://blog.csdn.net/luyaran/article/details/80075513

posted @ 2018-04-25 13:20  luyaran  阅读(214)  评论(0编辑  收藏  举报