Hướng dẫn string to int list python - chuỗi vào danh sách int python

Sự xen kẽ giữa các loại dữ liệu được tạo điều kiện bởi các thư viện Python khá dễ dàng. Nhưng vấn đề chuyển đổi toàn bộ danh sách các chuỗi thành số nguyên là khá phổ biến trong lĩnh vực phát triển. Hãy để thảo luận về một vài cách để giải quyết vấn đề cụ thể này. & NBSP;

Phương pháp 1: Sử dụng Eval ()

Chức năng Python Eval () phân tích đối số biểu thức và đánh giá nó như một biểu thức python và chạy biểu thức python (mã), nếu biểu thức là biểu diễn INT, Python chuyển đổi đối số thành một số nguyên.

Python3

lis

Modified list is: [1, 4, 3, 6, 7]
0
Modified list is: [1, 4, 3, 6, 7]
1
Modified list is: [1, 4, 3, 6, 7]
2
Modified list is: [1, 4, 3, 6, 7]
3
Modified list is: [1, 4, 3, 6, 7]
4
Modified list is: [1, 4, 3, 6, 7]
3
Modified list is: [1, 4, 3, 6, 7]
6
Modified list is: [1, 4, 3, 6, 7]
3
Modified list is: [1, 4, 3, 6, 7]
8
Modified list is: [1, 4, 3, 6, 7]
3__

Modified list is : [1, 4, 3, 6, 7]
2
Modified list is: [1, 4, 3, 6, 7]
0
Modified list is: [1, 4, 3, 6, 7]
1
Modified list is : [1, 4, 3, 6, 7]
5
Modified list is : [1, 4, 3, 6, 7]
6
Modified list is : [1, 4, 3, 6, 7]
7
Modified list is : [1, 4, 3, 6, 7]
8
Modified list is : [1, 4, 3, 6, 7]
9

Modified list is : [1, 4, 3, 6, 7]
1
Modified list is : [1, 4, 3, 6, 7]
2
Modified list is : [1, 4, 3, 6, 7]
3
Modified list is : [1, 4, 3, 6, 7]
4

Output:

Modified list is: [1, -4, 3, -6, 7]

Phương pháp 2: Phương pháp ngây thơ

Đây là phương pháp chung nhất tấn công bất kỳ lập trình viên nào trong khi thực hiện loại hoạt động này. Chỉ cần lặp qua toàn bộ danh sách và chuyển đổi từng chuỗi của danh sách thành int bằng cách loại đúc. & Nbsp;

Python3

Modified list is : [1, 4, 3, 6, 7]
5
Modified list is: [1, 4, 3, 6, 7]
0
Modified list is: [1, 4, 3, 6, 7]
1__12

Is

def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)
7
def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)
8
Modified list is: [1, 4, 3, 6, 7]
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
1

Modified list is : [1, 4, 3, 6, 7]
1
Modified list is : [1, 4, 3, 6, 7]
2
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
6
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
7

Output:

Modified list is: [1, 4, 3, 6, 7]

Phương pháp 3: Sử dụng danh sách hiểu & nbsp;list comprehension 

Đây chỉ là một loại bản sao của phương thức trên, chỉ được triển khai bằng cách sử dụng danh sách hiểu, một loại tốc ký mà một nhà phát triển luôn tìm kiếm. Nó tiết kiệm thời gian và độ phức tạp của việc mã hóa một giải pháp. & NBSP;

Python3

Modified list is : [1, 4, 3, 6, 7]
5
Modified list is: [1, 4, 3, 6, 7]
0
Modified list is: [1, 4, 3, 6, 7]
1__12

Is

def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)
7
def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)
8
Modified list is: [1, 4, 3, 6, 7]
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
1

Output:

Modified list is : [1, 4, 3, 6, 7]

Modified list is : [1, 4, 3, 6, 7]1Modified list is : [1, 4, 3, 6, 7]2['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types'] 4 ['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types'] 5 ['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types'] 6['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types'] 7map() 

Phương pháp 3: Sử dụng danh sách hiểu & nbsp;

Python3

Modified list is : [1, 4, 3, 6, 7]
5
Modified list is: [1, 4, 3, 6, 7]
0
Modified list is: [1, 4, 3, 6, 7]
1__12

Is

Modified list is : [1, 4, 3, 6, 7]
1
Modified list is : [1, 4, 3, 6, 7]
2
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
6
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
7

Output:

Modified list is : [1, 4, 3, 6, 7]

Phương pháp 3: Sử dụng danh sách hiểu & nbsp;

Đây chỉ là một loại bản sao của phương thức trên, chỉ được triển khai bằng cách sử dụng danh sách hiểu, một loại tốc ký mà một nhà phát triển luôn tìm kiếm. Nó tiết kiệm thời gian và độ phức tạp của việc mã hóa một giải pháp. & NBSP;

Python3

Modified list is : [1, 4, 3, 6, 7]
5
Modified list is: [1, 4, 3, 6, 7]
0
Modified list is: [1, 4, 3, 6, 7]
1
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
Modified list is : [1, 4, 3, 6, 7]
6
Modified list is : [1, 4, 3, 6, 7]
7

Modified list is : [1, 4, 3, 6, 7]
1
Modified list is : [1, 4, 3, 6, 7]
2
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
4
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
5
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
6
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
7

Modified list is : [1, 4, 3, 6, 7]
1
Modified list is : [1, 4, 3, 6, 7]
2
Modified list is : [1, 4, 3, 6, 7]
3
Modified list is : [1, 4, 3, 6, 7]
4

Output:

Modified list is: [1, 4, 4, 7, 7]

Phương pháp 4: Sử dụng Map () & NBSP;

Đây là phương pháp thanh lịch nhất, pythonic và được đề xuất để thực hiện nhiệm vụ cụ thể này. Hàm này được thực hiện riêng cho loại nhiệm vụ này và nên được sử dụng để thực hiện chúng. & NBSP;

def maybeMakeNumber(s):
    """Returns a string 's' into a integer if possible, a float if needed or
    returns it as is."""

    # handle None, "", 0
    if not s:
        return s
    try:
        f = float(s)
        i = int(f)
        return i if f == i else f
    except ValueError:
        return s

data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]

converted = list(map(maybeMakeNumber, data))
print(converted)

Output:

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']

Modified list is : [1, 4, 3, 6, 7]
5
Modified list is: [1, 4, 3, 6, 7]
0
Modified list is: [1, 4, 3, 6, 7]
11
Modified list is : [1, 4, 3, 6, 7]
2
Modified list is: [1, 4, 3, 6, 7]
13
Modified list is : [1, 4, 3, 6, 7]
2
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
0
Modified list is: [1, 4, 3, 6, 7]
16

from collections.abc import Iterable, Mapping

def convertEr(iterab):
    """Tries to convert an iterable to list of floats, ints or the original thing
    from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
    Does not work for Mappings  - you would need to check abc.Mapping and handle 
    things like {1:42, "1":84} when converting them - so they come out as is."""

    if isinstance(iterab, str):
        return maybeMakeNumber(iterab)

    if isinstance(iterab, Mapping):
        return iterab

    if isinstance(iterab, Iterable):
        return  iterab.__class__(convertEr(p) for p in iterab)


data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed", 
        ("0", "8", {"15", "things"}, "3.141"), "types"]

converted = convertEr(data)
print(converted)

Output:

['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed', 
 (0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order