Microsoft MVP성태의 닷넷 이야기
.NET Framework: 342. Python의 zip과 with 문 context를 C#과 비교하면. [링크 복사], [링크+제목 복사],
조회: 20765
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Python의 zip과 with 문 context를 C#과 비교하면.

python 2에서는 zip과 itertools.izip이 있고, 3에서는 izip이 zip으로 제공된다고 하는데요. tuple을 언어에 내장하다 보니 사용법 자체는 매우 간단합니다.

s = [1, 2, 3];
t = ["One", "Two", "Three"];

for x, y in zip(s, t):
    print str(x) + ": " + y

C#이라면 .NET 4.0부터 확장 메소드로 Enumerable.Zip이 있습니다.

Enumerable.Zip<TFirst, TSecond, TResult> Method 
; https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip

가끔 C# 질문글에 보면 foreach로 2개의 목록을 어떻게 열람할 수 있느냐는 것이 나오는데요. 즉 다음과 같은 식의 기능을 원하는 것입니다.

int[] numbers = { 1, 2, 3 };
string[] words = { "one", "two", "three" };

foreach (int n in numbers)
foreach (string txt in words)
{
    Console.WriteLine(n + ":" + txt);
}

물론, 위의 코드는 의도한 대로 동작하지 않습니다. 이런 경우 대부분의 답변은 그냥 for 문으로 돌려야 한다는 것인데, 아쉽게도 그건 배열에 한해서 적용될 뿐 IEnumerable 인터페이스를 구현한 경우에는 쓸 수가 없습니다.

바로 이런 경우에 파이썬처럼 다음과 같이 Tuple과 함께 Zip을 사용하면 해결할 수 있습니다.

int[] numbers = { 1, 2, 3 };
string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (first, second) => Tuple.Create(first, second));

foreach (var item in numbersAndWords)
    Console.WriteLine(item.Item1 + ", " + item.Item2);

참고로, numbers와 words의 배열 수가 다르면 작은 크기에 맞춰서 numbersAndWords의 수가 정해집니다.




그다음, 파이썬에는 __enter__, __exit__ 기능을 활용한 with 문 기능이 있습니다. 제가 보고 있는 책(Programming Insight 파이썬 완벽 가이드)에서는 이 기능의 예제로 "값 변경에 대한 트랜잭션 구현"을 제시하고 있는데 대략 다음과 같습니다.

class ValueTransaction(object):
    def __init__(self, firstValue):
        self.orgValue = firstValue
    def __enter__(self):
        self.copyValue = self.orgValue
    def __exit__(self, exctype, value, tb):
        if exctype is not None:
            self.orgValue = self.copyValue
    def setValue(self, newValue):
        self.orgValue = newValue

a = ValueTransaction(6)

try:
    with a:
        a.setValue(5)
        # raise RuntimeError("exception occurred!")  // 예외를 발생시키면 값은 6
except RuntimeError:
    pass

print a.orgValue

이 기능을 C#에서 구현할 수 있을까요? 넵. using과 IDisposable 인터페이스를 이용하면 다음과 같이 동일하게 구현할 수 있습니다.

public class ValueTransaction : IDisposable
{
    int? _orgValue;
    int? _copyValue;

    public int? Value { get { return _orgValue.Value; } }

    public ValueTransaction(int initValue)
    {
        _orgValue = initValue;
    }

    public void SetValue(int newValue)
    {
        _copyValue = newValue;
    }

    public void Dispose()
    {
        int exceptionCode = Marshal.GetExceptionCode();
        if (exceptionCode == 0)
        {
            if (_copyValue.HasValue == true)
            {
                _orgValue = _copyValue;
            }
        }
    }
}

ValueTransaction a = new ValueTransaction(6);

try
{
    using (a)
    {
        a.SetValue(5);
        // throw new ApplicationException(); // 예외가 발생하면 6
    }
}
catch (Exception) { }

Console.WriteLine(a.Value);

어쨌든, 확실히 C# 측의 코드가 길어지는 면이 있습니다. ^^ (Java는 C#의 using 문과 같은 기능이 7부터 제공된다고 합니다.)

첨부된 파일은 위의 코드를 담고 있는 솔루션 프로젝트입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/2/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2012-10-31 08시45분
[IOKLO] 와 Zip이란게 있었군요.. 저런 경우 많았는데 편하게 쓸수 있을것 같네요ㅎ Zip하는 부분은 numbers.Zip(words, Tuple.Create) 으로 더 간단하게 쓸 수 있을거 같아요
[guest]
2012-10-31 12시39분
IOKLO 님 ^^ 좋은 의견 감사합니다. new보다는 단순하게 Tuple.Create가 더 명쾌한 표현이 되겠군요. ^^ (본문에 반영했습니다.)
정성태
2012-11-01 12시59분
[ryujh] using 문 바깥에 초기화 하길래 참조오류 생각을 했는데

멤버가 값형식이고 dispose 할 필요없으니

대신 예외처리 시 using 블럭 벗어날때 dispose 호출하도록 트랜잭션을 구현한 것이군요.

도움많이되었습니다.
[guest]

... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12876정성태12/14/20217179개발 환경 구성: 616. Custom Sources를 이용한 Azure Monitor Metric 만들기
12875정성태12/13/20216822스크립트: 35. python - time.sleep(...) 호출 시 hang이 걸리는 듯한 문제
12874정성태12/13/20216862오류 유형: 773. shell script 실행 시 "$'\r': command not found" 오류
12873정성태12/12/20217996오류 유형: 772. 리눅스 - PATH에 등록했는데도 "command not found"가 나온다면?
12872정성태12/12/20217839개발 환경 구성: 615. GoLang과 Python 빌드가 모두 가능한 docker 이미지 만들기
12871정성태12/12/20217871오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/20216423개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/20218733개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
12868정성태12/7/20217350오류 유형: 770. twine 업로드 시 "HTTPError: 400 Bad Request ..." 오류 [1]
12867정성태12/7/20217003개발 환경 구성: 612. 파이썬 - PyPI 패키지 만들기 (3) entry_points 옵션
12866정성태12/7/202114388오류 유형: 769. "docker build ..." 시 "failed to solve with frontend dockerfile.v0: failed to read dockerfile ..." 오류
12865정성태12/6/20217135개발 환경 구성: 611. 파이썬 - PyPI 패키지 만들기 (2) long_description, cmdclass 옵션
12864정성태12/6/20215527Linux: 46. WSL 환경에서 find 명령을 사용해 파일을 찾는 방법
12863정성태12/4/20217465개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기
12862정성태12/3/20216164오류 유형: 768. Golang - 빌드 시 "cmd/go: unsupported GOOS/GOARCH pair linux /amd64" 오류
12861정성태12/3/20218422개발 환경 구성: 609. 파이썬 - "Windows embeddable package"로 개발 환경 구성하는 방법
12860정성태12/1/20216454오류 유형: 767. SQL Server - 127.0.0.1로 접속하는 경우 "Access is denied"가 발생한다면?
12859정성태12/1/202112694개발 환경 구성: 608. Hyper-V 가상 머신에 Console 모드로 로그인하는 방법
12858정성태11/30/20219954개발 환경 구성: 607. 로컬의 USB 장치를 원격 머신에 제공하는 방법 - usbip-win
12857정성태11/24/20217282개발 환경 구성: 606. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법
12856정성태11/23/20219208.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216413개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20218088개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216365오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217871스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20219029오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...